如何在Java中通过终端执行python脚本

时间:2017-11-02 17:16:19

标签: java python macos terminal

我试图通过终端运行python脚本,但它总是引发异常:没有这样的文件或目录

StringBuffer output = new StringBuffer();

String command = "python3 Users/lounah/Documents/programming/ApplicationName/scriptName.py " + params.toString();

ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();

BufferedReader reader =
        new BufferedReader(new InputStreamReader(process.getInputStream()));

String line;
while ((line = reader.readLine())!= null) {
    output.append(line + "\n");
}

1 个答案:

答案 0 :(得分:0)

当您在ProcessBuilder中传递字符串时,它会尝试运行位于该路径中的程序 Instaed你应该使用String[]和可执行文件的路径('/python3/python.exe''python''py'),然后是脚本的路径,后跟参数。

String[] command = {
    "python3",
    "Users/lounah/Documents/programming/ApplicationName/scriptName.py", 
    params.toString()
};
ProcessBuilder processBuilder = new ProcessBuilder(command);