运行 python 来自 jar 文件的脚本

Running python script from jar file

我一直在开发 java 应用程序,该应用程序使用 python 脚本来 运行 一些 3d 可视化,它在我从 intellij 运行ning 它时工作但是有一次我创建了 jar 文件,但它没有 运行。 OS: MAC OS

我如何运行编写脚本: Process p1 = Runtime.getRuntime().exec("python3 vizualize3D.py");

假设脚本在 jar 文件中,您可以从资源中获取输入流,并将其用作从 python 解释器创建的 Process 的输入:

// Note: the path to the script here is relative to the current class
// and follows strict resource name rules, since this is in a jar file
InputStream script = getClass().getResourceAsStream("visualize3D.py");

// The following creates a process to run python3.
// This assumes python3 is on the system path. Provide the full
// path to the python3 interpreter (e.g. /usr/bin/python3) if it's
// not on the path.

// The - option to python3 instructs it to execute a script provided
// as standard input.

Process process = new ProcessBuilder("python3", "-")
    .start() ;
OutputStream out = process.getOutputStream();
byte[] buffer = new byte[1024];
int read = 0;
while((read = script.read(buffer)) != -1) {
    pos.write(buffer, 0, read);
}
script.close();

有关获取脚本正确路径的详细信息,请参阅

问题有多个层次和解决方案: 1. 我没有把 .py 文件放在 jar 构建配置中 2. 把它放好后,我总是得到一个异常,它是空的,因为代码中有错别字 3. 在尝试了很多方法 运行 之后,这个成功了 .重要的是检查您是否将 py 文件添加到构建配置中并以正确的方式 运行 它因为 python 不能 运行t 来自 zip 和压缩状态的文件。