Executing a python file from within JAR

2020-04-14 07:08发布

问题:

I am trying to figure out how to reference a python file so that I can execute it within a Java GUI Jar. It needs to be a portable solution, so using absolute paths will not work for me. I have listed my project structure below, and have included the code for how I am trying to execute the python script..I have read things about using resources, but I have been unable to implement this successfully. I appreciate any help you can provide!

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:

Starting a file path with a / means you want to start at the root of your file system.

Your code worked for me by simply removing that leading slash:

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

The reason why putting a wrong file did not show an error is because this java code only displays the input stream (getInputStream()), not the error stream (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