Run a Python Script from Java

This question already has an answer here:

  • Java Python Integration

    8 answers

I want to run a Python2 Script from my Java application but it doesn’t run.

I don’t get any Stack or Error – It just does not run!

I tried this:

public void execPython2(String file, String parm0) {
    try {
        Process p = new ProcessBuilder("python2", file, parm0).start();
    } catch (Exception e) {
    }
}

Here is the method call:

public String getMAC(String IP_Addr) {
    execPython2("getMacAddr.py", IP_Addr);    
    try {
        Thread.sleep(500);
    } catch (Exception e) {
    }

    String macAddr[] = readFromFile("lastMac.log", false);    
    try {
        Thread.sleep(500);
    } catch (Exception e) {
    }

    return macAddr[0];
}

The python2 script will create a “lastMac.log” file.

At first I thought the python script would not be finished and I just have to wait until it is finished but i guess the Python script is not even running.

Python is a script language – it needs an interpreter to be executed.

So, to be on the safe side – build a comment like

 full-path-to-binary/python full-path-to-your-script/yourscript.py

When you are using a unix-like Operating System and when you are writing your script to contain a correct #!/path/to/python statement in its first line, and when the script has r+x file system permissions you might not need to do so.

The next step then: your code is ignoring any exception. Consider checking error messages instead of ignoring them.