[英]Run shell commands in Elixir
我想通过我的 Elixir 代码执行一个程序。 对给定字符串调用 shell 命令的方法是什么? 有什么不是平台特定的吗?
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 调用需要一个字符列表而不是二进制文件,因此您需要类似以下内容:
"find /tmp -type f -size -200M |xargs rm -f" |> String.to_char_list |> :os.cmd
你可以看看Erlang os Module 。 例如cmd(Command) -> string()
应该是你要找的。
"devinus/sh" 库是另一种有趣的运行 shell 命令的方法。
我不能直接链接到相关的文件,但它是在这里下System
模块
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.
如果我在文件ac
有以下 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() 函数的返回值。
也可以像这样使用 erlang 的:os
模块:
iex(3)> :os.cmd('time')
'\nreal\t0m0.001s\nuser\t0m0.000s\nsys\t0m0.000s\n'
请注意,在处理结果时,您必须处理 erlang 二进制文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.