我正在尝试执行java代码中的.py文件。我将.py文件移动到java项目的默认目录中,并使用以下代码调用它:
String cmd = "python/";
String py = "file";
String run = "python " +cmd+ py + ".py";
System.out.println(run);
//Runtime.getRuntime().exec(run);
Process p = Runtime.getRuntime().exec("python file.py");
无论是使用变量run,还是使用完整路径或“file.py file.py”,我的代码都在运行,其中显示了在没有执行python的情况下总时间为0秒的消息build successful。我的问题出在哪里?
发布于 2014-12-03 17:04:56
我相信我们可以使用ProcessBuilder
Runtime.getRuntime().exec("python "+cmd + py + ".py");
.....
//since exec has its own process we can use that
ProcessBuilder builder = new ProcessBuilder("python", py + ".py");
builder.directory(new File(cmd));
builder.redirectError();
....
Process newProcess = builder.start();
发布于 2018-06-04 02:41:10
String command = "cmd /c python <command to execute or script to run>";
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader bre = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line;
while ((line = bri.readLine()) != null) {
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null) {
System.out.println(line);
}
bre.close();
p.waitFor();
System.out.println("Done.");
p.destroy();
发布于 2017-07-13 01:04:15
您可以运行python脚本
Process p = Runtime.getRuntime().exec(PYTHON_ABSOLUTE_PATH, script_path)
要获取PYTHON_ABSOLUTE_PATH,只需键入
which python2.7
在终端中
https://stackoverflow.com/questions/27267391
复制相似问题