从 Java 运行.py文件

2022-09-02 23:24:03

我正在尝试从java代码执行.py文件。我将.py文件移动到java项目的默认dir中,并使用以下代码调用它:

    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,要么使用整个路径或“python file.py”,我的代码正在运行,显示消息构建成功,总时间为 0 秒,而无需执行 file.py。我在这里的问题是什么?


答案 1

您也可以像这样使用:

String command = "python /c start python path\to\script\script.py";
Process p = Runtime.getRuntime().exec(command + param );

String prg = "import sys";
BufferedWriter out = new BufferedWriter(new FileWriter("path/a.py"));
out.write(prg);
out.close();
Process p = Runtime.getRuntime().exec("python path/a.py");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ret = in.readLine();
System.out.println("value is : "+ret);

从 Java 运行 Python 脚本


答案 2

我相信我们可以使用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();