java - 从 JAR 中执行 python 文件

标签 java python netbeans jar

我想弄清楚如何引用 python 文件,以便我可以在 Java GUI 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

最佳答案

/ 开头的文件路径意味着您希望从文件系统的根目录开始。

您的代码只需删除前导斜线即可为我工作:

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

关于java - 从 JAR 中执行 python 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25369490/

相关文章:

python - 如何将清理后的文本数据拆分为训练数据集和测试数据集(随机采样除外)

java - 为什么没有整数输出

java - 作为 Web 服务客户端的 Netbeans 富客户端平台 RCP 应用程序

Java 数组 - 来自测试

java - 使用 twitter 4j 在 twitter 中扩展推文中的链接

java - 当 "inLocale"设置为土耳其语 (JDK 1.6.0_29) 时可用的语言环境显示国家?

python - 由于缺少 js 文件,Jupyter 无法加载

python - 冲突的进口

java - netbeans 中的默认 glassfish 4.0 密码

Java lambda 表达式 : Copy nodes from list to a new list