从 Java jar 文件调用 python 脚本

Calling a python script from a Java jar file

我正在使用 Java 和 Python 开发一个项目,GUI 使用 Java,后端使用 Python。当使用以下代码按下按钮时,Java 程序会调用 Python 脚本:

Runtime r = Runtime.getRuntime();
String pyScript = "resources/script.py";
String scriptPath = getClass().getResource(pyScript).toExternalForm();
// Strip "file/" from path
scriptPath = scriptPath.substring(scriptPath.indexOf("/") + 1);
Process p = r.exec("python " + scriptPath)

python 脚本位于 Java 项目的 src 文件夹中名为 resources 的文件夹中。当我 运行 我的程序在我的 IDE (IntelliJ) 中时,这段代码有效,但是当我创建一个 .jar 文件并尝试 运行 脚本时,什么也没有发生。我可以确认该程序仍然在 .jar 文件中找到脚本。 我怎样才能得到 运行 的脚本?

在此解决方案中,如果文件存在,我们 运行 脚本。该脚本可以位于完整路径或相对路径上。该脚本不在 jar 文件中。

TestPython.java

import java.lang.*;
import java.io.*;

public class TestPython {
    public static void main(String[] args) {

        System.out.println("I will run a Python script!");
        Runtime r = Runtime.getRuntime();
        String pyScript = "py/test.py";

        File f = new File(pyScript);
        if (f.exists() && !f.isDirectory()) {
            try {
                Process p = r.exec("python " + pyScript);
                BufferedReader in = new BufferedReader(
                    new InputStreamReader(p.getInputStream()));
                String line = null;
                while ((line = in .readLine()) != null) {
                    System.out.println(line);
                }
                System.out.println("Python script ran!!");
            } catch (Exception ex) {
                System.out.println("Something bad happened!!");
                ex.printStackTrace();
            }
        } else {
            System.out.println("Unexistent file!" + pyScript);
        }
    }
}

py/test.py

print("I'm a Python script!!!")

Output:

I will run a Python script!

I'm a Python script!!!

Python script ran!!