Search code examples
javapythonmacospython-3.xprocessbuilder

Java ProcessBuilder on Mac OSX doesn't see Python 3


I'm trying to run a Python script from Java using ProcessBuilder. The script requires Python 3 at a minimum. I'm calling it like this:

// the -u is for unbuffered output
String[] pythonCommand = {"python", "-u", "script.py"};
ProcessBuilder ps = new ProcessBuilder(pythonCommand);
Process pr = pb.start();

It works completely fine on Windows, and when I define script.py to print out the Python version with sys.version_info it tells me that I am running Python 3.6.2

However, on my friend's Macbook, the script doesn't work and sys.version_info shows Python 2.7.1. She installed Python 3 using homebrew with brew install python3. When she runs python3 scriptname.py from terminal, it runs on Python 3.6.2 but python scriptname.py runs on Python 2.7.1 from Terminal.

Because of that, I thought I could just change the Java ProcessBuilder command to be

String[] pythonCommand = {"python3", "-u", "script.py"}; // python3

if the OS name doesn't start with Windows, but that command doesn't work from Java's processbuilder on Mac OS—it throws

java.io.IOException: Cannot run program "python3": error=2, No such file or directory

I'm thinking this is a problem with the path that the ProcessBuilder is using to run Python, does that sound right? Maybe I need to try to use virtualenv to run Python 3 on Mac, but I have no idea how to do that. Or, could it be something completely different?


Solution

  • I ended up going away from this approach entirely since it relied on Python and all the required modules being installed on the user's computer. Instead, I packaged my Python scripts into executables with Pyinstaller, put them into the Java resources folder, and called the compiled executables from the Java ProcessBuilder.