简体   繁体   English

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

[英]how can i execute python script via terminal in Java

Im trying to run python script via terminal but it always throws an exception: No such file or directory 我试图通过终端运行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");
}

When you pass a string in ProcessBuilder it tries to run a program located in that path. ProcessBuilder传递字符串时,它将尝试运行位于该路径中的程序。
Instaed you should use a String[] with the path of your executable ( '/python3/python.exe' or 'python' or 'py' ) followed by the path of your script, followed by the arguments. 应当在您的可执行文件的路径( '/python3/python.exe''python''py' )后面加上String[] ,然后是脚本的路径,再加上参数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM