Search code examples
pythonjavaprocessscriptingprocessbuilder

Java ProcessBuilder class can't run .py script


I have a program that builds a set of processes that need to execute a main.py script but with different parameters between them. The scripts have the following form:

python C:/Users/us/Git/main.py 2 24 C:/Users/us/Git/output
python C:/Users/us/Git/main.py 24 48 C:/Users/us/Git/output

In Java I use the ProcessBuilder to run the process:

for (int i = 0; i < cores; i++) {
    ProcessBuilder pb;
    if (i == 0) {
        pb = new ProcessBuilder("python", scriptPath, "" + 2, "" + (last + subpart + diff) + "", "" + currentPath + "\\output");
        last = last + subpart + diff;
    } else {
        pb = new ProcessBuilder("python", scriptPath, "" + last, "" + (last + subpart) + "", "" + currentPath + "\\output");
        last = last + subpart;
    }
    builders[i] = pb;
}
for (int i = 0; i < cores; i++) {
    processes[i] = builders[i].start();
}
System.out.print("waiting for " + processes.length + " processes to end");

But, everytime I run the Java program, it seems that the ProcessBuilder didn't run the script... why? How can I resolve?

I'm currently using Intellij as IDE.

I've tried to build the project and the run the .jar file and, it seems to work. But what I actually need is to run the scripts without building the project everytime

Why I think the ProcessBuilder dosen't run the scripts?

The scripts after running, have to produce some files after clustering process, and these files have to be inside the output directory. When the java code, after processes finished, go to search for this files, it dosen't find them. In fact, the Exeption thrown is:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.io.File.getName()" because "winner" is null

Solution

  • The error was in the environment variables. I had two environment variables, one pointing to python.exe and the other pointing to a Python/Scripts folder, the latter of which was located within the directory of the python.exe file. It seems, for some strange reason, that java was calling the Scripts folder to execute the script I was passing as input to the process builder class. So I removed that environment variable then proceeded to update all the libraries used in the python script.