小编典典

从JAR中执行python文件

java

我试图弄清楚如何引用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

阅读 196

收藏
2020-11-26

共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
2020-11-26