无法从Java Jar运行python脚本

devfoFikiCar:

在IntelliJ中工作时,一切正常,但是在我构建jar之后,它停止了。一开始,只是我忘记了将其放在jar build config中,但是现在确保它已经存在之后,我仍然无法运行它。这些是我尝试的方法:

InputStream script = mainView.class.getResourceAsStream("vizualize3D.py");
Process process = new ProcessBuilder("python3", "-").start() ;

Process p1 = Runtime.getRuntime().exec("python3 " + script);

Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("python3 " + mainView.class.getResourceAsStream("vizualize3D.py"));

尽管有资源,但没有主题工作。我还尝试在IntelliJ项目中指定它的路径,并且它只能在我从jar启动后从IntelliJ运行时才起作用。

Edit1:对于不了解py文件的人,jar文件中

James_D:

涉及您尝试执行的选项"python3 "+script和等效项均无效。scriptInputStream,而不是文件系统上的路径,因此仅将其与串联String不会给您带来任何有意义的意义。另外,由于您的脚本不在自己的文件中,并且python解释器没有提取它的简单方法,因此像这样简单地调用它是行不通的。

但是,您可以做的是执行

python3 -

-这里选项(至少在类似BSD的系统上)意味着“从标准输入中读取,并将其解释为脚本”。然后,在Java端,您可以将jar打包的资源读取为流,并将其通过管道传递到python进程的标准输入。

有关为资源选择正确路径的详细信息,请参见如何为JavaFX应用程序所需的FXML文件,CSS文件,图像和其他资源确定正确的路径?

下面的脚本对我有用:在该脚本中,脚本仅与该类放在同一包中:

PythonRunner.java:

package example.python;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class PythonRunner {

    public static void main(String[] args) throws Exception {

        String pythonInterpreter = "/usr/bin/python3" ; // default
        if (args.length > 0) {
            pythonInterpreter = args[0] ;
        }

        InputStream script = PythonRunner.class.getResourceAsStream("script.py");
        Process pythonProcess = new ProcessBuilder(pythonInterpreter, "-")
                .start();

        // This thread reads the output from the process and 
        // processes it (in this case just dumps it to standard out)
        new Thread(() ->  {
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(pythonProcess.getInputStream()))) {

                for (String line ; (line = reader.readLine()) != null ;) {
                    System.out.println(line);
                }
            } catch (IOException exc) {
                exc.printStackTrace();
            }
        }).start();

        // read the script from the resource, and pipe it to the
        // python process's standard input (which will be read because
        // of the '-' option)
        OutputStream stdin = pythonProcess.getOutputStream();
        byte[] buffer = new byte[1024];
        for (int read = 0 ; read >= 0 ; read = script.read(buffer)) {
            stdin.write(buffer, 0, read);
        }
        stdin.close();
    }

}

script.py:

import sys

for i in range(10):
    print("Spam")

sys.exit(0)

清单文件

Manifest-Version: 1.0
Main-Class: example.python.PythonRunner

Eclipse布局:

在此处输入图片说明

Jar的内容和运行结果:

$ jar tf runPython.jar 
META-INF/MANIFEST.MF
example/python/PythonRunner.class
example/python/script.py
$ java -jar runPython.jar 
Spam
Spam
Spam
Spam
Spam
Spam
Spam
Spam
Spam
Spam
$

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章