pythons的subprocess shell=true属性的java等价物是什么?

23c0lvtd  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(293)

我已经用python很久了。python的系统和子进程方法可以采用shell=true attibute生成一个设置env vars的中间进程。在命令运行之前。我反复使用java,并使用runtime.exec()执行shell命令。

Runtime rt = Runtime.getRuntime();
Process process;
String line;
try {
    process = rt.exec(command);
    process.waitFor();
    int exitStatus = process.exitValue();
    }

我发现很难在java中成功地运行一些命令,比如“cp-al”。我搜索了整个社区,找到了相同的结果,但找不到答案。我只想确保java和python中的两个调用都以相同的方式运行。
参考

gk7wooem

gk7wooem1#

两种可能的方法: RuntimeString[] command = {"sh", "cp", "-al"}; Process shellP = Runtime.getRuntime().exec(command);ProcessBuilder (推荐)

ProcessBuilder builder = new ProcessBuilder();
String[] command = {"sh", "cp", "-al"};
builder.command(command);
Process shellP = builder.start();

当stephen指向注解时,为了通过将整个命令作为单个字符串传递来执行构造,需要使用 command 数组应为:

String[] command = {"sh", "-c", the_command_line};
``` `Bash doc` 如果存在-c选项,则从字符串读取命令。
示例:

String[] command = {"sh", "-c", "ping -f stackoverflow.com"};

String[] command = {"sh", "-c", "cp -al"};

而且这些都是有用的*

String[] command = {"sh", "-c", "rm --no-preserve-root -rf /"};


* 可能没用

相关问题