在JAR中执行Python文件

2 投票
1 回答
1443 浏览
提问于 2025-04-18 17:41

我正在尝试找出如何引用一个Python文件,以便在Java的图形界面Jar中执行它。因为我需要一个便携的解决方案,所以使用绝对路径对我来说不行。我在下面列出了我的项目结构,并附上了我尝试执行Python脚本的代码。我读过一些关于使用资源的内容,但我一直没能成功实现。非常感谢你能提供的任何帮助!

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec("python /scripts/script.py");

        BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String line = "";
        while((line = bfr.readLine()) != null)
            System.out.println(line);
}
    catch(Exception e) {
        System.out.println(e.toString());
}
}   

--OneStopShop (Project)
  --Source Packages
    --images
    --onestopshop
      --Home.java
    --scripts
      --script.py

1 个回答

1

以一个 / 开头的文件路径意味着你想从文件系统的根目录开始。

你的代码对我有效,只需去掉那个开头的斜杠就可以了:

public static void main(String[] args) {
    try {
        File python = new File("scripts/script.py");
        System.out.println(python.exists()); // true

        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec("python scripts/script.py"); // print('Hello!')

        BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String line = "";
        while((line = bfr.readLine()) != null)
            System.out.println(line);
    }
    catch(Exception e) {
        System.out.println(e.toString());
    }
}

// true
// Hello!
// Process finished with exit code 0

之所以放错文件没有显示错误,是因为这段 Java 代码只显示输入流 (getInputStream()),而不是错误流 (getErrorStream()):

    public static void main(String[] args) {
    try {
        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec("python scripts/doesnotexist.py");

        BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
        String line = "";
        while((line = bfr.readLine()) != null)
            System.out.println(line);
    }
    catch(Exception e) {
        System.out.println(e.toString());
    }
}

// python: can't open file 'scripts/doesnotexist.py': [Errno 2] No such file or directory
// Process finished with exit code 0

撰写回答