Search code examples
javapythonpywin32

Calling a python script from a Java jar file


I am working on a project using Java and Python using Java for the GUI and Python for the backend. The Java program calls a Python script when a button is pressed using the following code:

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)

The python script is located in a folder called resources in the src folder of the Java project. This code works when I run my program in my IDE (IntelliJ) however when I create a .jar file and attempt to run the script nothing occurs. I can confirm that the program does still find the script within the .jar file. How can I get the script to run?


Solution

  • In this solution, we run the script if the file exists. The script could be on a full or relative path. The script is not in the jar file.

    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!!