Python 的子进程 shell=True 属性 的 Java 等价物是什么?
what is the Java equivalent of Pythons's subprocess shell=True property?
我已经使用 python 很长时间了。 python 的系统和子进程方法可以采用 shell=True 属性来生成设置环境变量的中间进程。在命令 运行s 之前。我一直在使用 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 运行 中的调用都以相同的方式进行。
refer
两种可能的方式:
-
String[] 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};
If the -c option is present, then commands are read from
string.
示例:
String[] command = {"sh", "-c", "ping -f whosebug.com"};
String[] command = {"sh", "-c", "cp -al"};
而且总是有用的*
String[] command = {"sh", "-c", "rm --no-preserve-root -rf /"};
*可能没有用
我已经使用 python 很长时间了。 python 的系统和子进程方法可以采用 shell=True 属性来生成设置环境变量的中间进程。在命令 运行s 之前。我一直在使用 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 运行 中的调用都以相同的方式进行。
refer
两种可能的方式:
-
String[] 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};
If the -c option is present, then commands are read from string.
示例:
String[] command = {"sh", "-c", "ping -f whosebug.com"};
String[] command = {"sh", "-c", "cp -al"};
而且总是有用的*
String[] command = {"sh", "-c", "rm --no-preserve-root -rf /"};
*可能没有用