如何在Erlang中执行系统命令并使用os:cmd/1获得结果? [英] How to execute system command in Erlang and get results using os:cmd/1?
问题描述
当我尝试执行以下返回错误或在Windows上不退出的命令时-我总是得到空列表,而不是以字符串形式返回错误,例如:
When I try to execute following command that returns error or doesn't exit on Windows - I always get empty list instead of error returned as string so for example:
我得到:
[] = os:cmd("blah").
代替
"command not found" = os:cmd("blah").
在linux中-一切正常,因此我得到了"/bin/sh:第1行:等等:找不到命令\ n"
In linux - everything works as expected so I get "/bin/sh: line 1: blah: command not found\n"
因此,当我需要知道执行的完成方式等时,我不能依赖该功能. 请提出一些通用的方法来执行命令并获得包括错误代码在内的结果.
Therefore I cannot rely on that function when I need to know how execution finished etc. Please suggest some general way how to execute command and get results including error code.
谢谢!
推荐答案
I am not familiar with windows at all, but I'm sure, you should look this. This is implementation os:cmd/1
function.
os:cmd/1
有问题.该功能不会告诉您命令执行是否成功,因此您仅需依赖某些命令外壳行为(取决于平台)即可.
There is problem with os:cmd/1
. This function doesn't let you know, was command execution successful or not, so you only have to rely on certain command shell behaviour (which is platform dependent).
我建议您使用erlang:open_port/2
功能.像这样的东西:
I'd recommend you to use erlang:open_port/2
function. Something like that:
my_exec(Command) ->
Port = open_port({spawn, Command}, [stream, in, eof, hide, exit_status]),
get_data(Port, []).
get_data(Port, Sofar) ->
receive
{Port, {data, Bytes}} ->
get_data(Port, [Sofar|Bytes]);
{Port, eof} ->
Port ! {self(), close},
receive
{Port, closed} ->
true
end,
receive
{'EXIT', Port, _} ->
ok
after 1 -> % force context switch
ok
end,
ExitCode =
receive
{Port, {exit_status, Code}} ->
Code
end,
{ExitCode, lists:flatten(Sofar)}
end.
因此函数my_exec/1
将返回进程退出代码以及进程标准输出.
So function my_exec/1
will return process exit code along with process stdout.
这篇关于如何在Erlang中执行系统命令并使用os:cmd/1获得结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!