【发布时间】:2017-07-23 00:10:12
【问题描述】:
我正在使用ProcessBuilder来构建我的命令。我想在这篇文章之后构建我的命令:How do I launch a java process that has the standard bash shell environment?
也就是说,我的命令是这样的:
/bin/bash -l -c "my program"
但是,我很难将双引号传递给ProcessBuilder,因为如果我将双引号本身添加到List<String> command,new ProcessBuilder(List<String> command) 无法表达命令。 ProcessBuilder 将双引号识别为参数。
相关代码:
//Construct the argument
csi.add("/bin/bash");
csi.add("-l");
csi.add("-c");
csi.add("\"");
csi.add(csi_path);
csi.add(pre_hash);
csi.add(post_hash);
csi.add("\"");
String csi_output = Command.runCommand(project_directory, csi);
public static String runCommand(String directory, List<String> command) {
ProcessBuilder processBuilder = new ProcessBuilder(command).directory(new File(directory));
Process process;
String output = null;
try {
process = processBuilder.start();
//Pause the current thread until the process is done
process.waitFor();
//When the process does not exit properly
if (process.exitValue() != 0) {
//Error
System.out.println("command exited in error: " + process.exitValue());
//Handle the error
return readOutput(process);
}else {
output = readOutput(process);
System.out.println(output);
}
} catch (InterruptedException e) {
System.out.println("Something wrong with command: " +e.getMessage());
} catch (IOException e) {
System.out.println("Something wrong with command: " +e.getMessage());
}
return output;
}
Ps:我确实想使用ProcessBuilder 而不是Runtime.getRuntime.exec(),因为我需要在特定目录中运行命令。我需要使用ProcessBuilder.directory()。
Ps:该命令运行后会以2退出。系统似乎可以识别此命令。奇怪的是用2退出后没有输出。
Ps:预期的命令是/bin/bash -l -c "/Users/ryouyasachi/GettyGradle/build/idea-sandbox/plugins/Getty/classes/python/csi 19f4281 a562db1"。我打印了这个值,它是正确的。
【问题讨论】:
-
您不需要这样做。
List中的每个元素都将作为单独的参数传递给命令,因此只需将List<String>传递给ProcessBuilder -
在我看来,这意味着将
new ProcessBuilder(sb.toString())更改为new ProcessBuilder(command) -
请记住,在命令行中使用
"..."的原因是为了否定空格,因此引号之间的所有内容都作为单个参数传递给进程 -
@MadProgrammer 我试过你的方法,但命令仍然以 2 退出。似乎问题在于添加
/bin/bash -l -c,因为没有它my program运行正常。 -
@JiaxiangLiang 用您最近尝试的内容更新您的帖子。