在Elixir中运行shell命令

时间:2014-03-23 18:15:54

标签: elixir

我想通过我的Elixir代码执行程序。将shell命令调用给定字符串的方法是什么?有什么不是特定于平台的吗?

6 个答案:

答案 0 :(得分:79)

以下是执行不带参数的简单shell命令的方法:

System.cmd("whoami", [])
# => {"lukas\n", 0}

查看有关System的文档以获取更多信息。

答案 1 :(得分:11)

您可以查看Erlang os Module。例如。 cmd(Command) -> string()应该是你想要的。

答案 2 :(得分:9)

" devinus / sh" library是另一种运行shell命令的有趣方法。

https://github.com/devinus/sh

答案 3 :(得分:5)

我无法直接链接到相关文档,但System模块下的here

cmd(command) (function) # 
Specs:

cmd(char_list) :: char_list
cmd(binary) :: binary
Execute a system command.

Executes command in a command shell of the target OS, captures the standard output of the command and returns the result as a binary.

If command is a char list, a char list is returned. Returns a binary otherwise.

答案 4 :(得分:5)

System.cmd / 3似乎接受命令的参数作为列表,并且当您尝试在命令名中隐藏参数时不高兴。  例如

System.cmd("ls", ["-al"]) #works, while
System.cmd("ls -al", []) #does not.

下面实际发生的是System.cmd / 3调用:os.find_executable / 1及其第一个参数,对于像ls这样的东西可以正常工作但是例如对于ls -al返回false。

erlang调用需要一个char列表而不是二进制文件,因此您需要类似以下内容:

"find /tmp -type f -size -200M |xargs rm -f" |> String.to_char_list |> :os.cmd

答案 5 :(得分:1)

如果文件a.c中有以下c程序:

#include <stdio.h>
#include <stdlib.h>

int main(int arc, char** argv)
{

    printf("%s\n",argv[1]);
    printf("%s\n",argv[2]);

    int num1 = atoi(argv[1]);
    int num2 = atoi(argv[2]);

    return num1*num2;
}

并将程序编译为文件a

~/c_programs$ gcc a.c -o a

然后我可以做:

~/c_programs$ ./a 3 5
3
5

我可以这样获得main()的返回值:

~/c_programs$ echo $?
15

类似地,在iex中,我可以这样做:

iex(2)> {output, status} = System.cmd("./a", ["3", "5"])
{"3\n5\n", 15}

iex(3)> status
15

System.cmd()返回的元组的第二个元素是main()函数的返回值。