简体   繁体   中英

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?

Homebrew does not always link the actual python3 executable to a directory that is in the PATH . You should check this with the terminal.

On my MacBook the python3 is linked at /usr/local/bin/python3

xvolks@localhost ~> ls -l /usr/local/bin/python3
lrwxr-xr-x  1 xvolks  admin  35 19 aoû 00:02 /usr/local/bin/python3 -> ../Cellar/python3/3.6.2/bin/python3

If the link is missing you can use the command brew link python3 to create it.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM