我想运行一个名为foo的python脚本。我有一条荒谬的道路,让我们说: /用户/ ME / pythonscripts /
我试过跑:
String cmd="/Users/me/pythonscripts/"
String py="foo"
Runtime.getRuntime().exec("cd "+cmd);
Runtime.getRuntime().exec("python "+py+".py");
但是这确实运行了python文件。
答案 0 :(得分:4)
尝试使用更像......
的内容Runtime.getRuntime().exec("python "+cmd + py + ".py");
相反。每个exec
都是它自己的流程,多个exec
彼此没有关系...
您还应该考虑使用ProcessBuilder
,因为这为您提供了很高级别的可配置性,例如,您可以更改执行路径上下文...
ProcessBuilder pb = new ProcessBuilder("python", py + ".py");
pb.directory(new File(cmd));
pb.redirectError();
//...
Process p = pb.start();
另外,请注意,Python的输出流存在问题,这可能会阻止Java在完全完成之前读取它...
有关详细信息,请查看Java: is there a way to run a system command and print the output during execution?
此外,请确保python
在shell的搜索路径中,否则您还需要指定该命令的完整路径
答案 1 :(得分:1)
这对我有用
public static void main(String[] args) throws IOException{
Runtime runtime = Runtime.getRuntime();
Process p1 = runtime.exec("D:\\programs\\Anaconda3\\Scripts\\spyder.exe \"C:\\Users\\Al-Hanouf\\codes\\PageRank.py\"");
System.out.print("is process alive = "+p1.isAlive());
}