简体   繁体   中英

Java calls wrong python version

I'm trying to run a Python script from a Java program using Process and ProcessBuilder, however Java keeps using the wrong version of Python. (The script needs 3.6.3 to run and Java runs Python 2.7)

However when I run the script from the terminal (outside of Java), it runs the correct Python (3.6.3). How does one change what version of Python gets run when called by Java?

The short version is it changes with your PATH environment variable.

Under Windows, Technet has the answer. Scroll down to the 'Command Search Sequence' section. This answer explains it nicely.

For UNIX-like OS's, this answer is nicely detailed.

There are two very useful commands for determining which executable is going to be called: which for UNIX-likes and where for newer Windows.

The most likely reason for the difference between Java and the terminal is a difference in your PATH . Perhaps your Java version is being run with a modified PATH ? A launch script of some kind may be changing it.

Add /usr/bin/python3.4 to the start of your command to force the version of python you want. If you're not sure where python is installed, have a go at using whereis python and seeing what you get back.

private int executeScript(final List<String> command) {
    try {
        final ProcessBuilder processBuilder = new ProcessBuilder("/usr/bin/python3.4").command(command);
        processBuilder.redirectErrorStream(true);

        System.out.println("executing: " + processBuilder.command().toString());

        final Process process = processBuilder.start();
        final InputStream inputStream = process.getInputStream();
        final InputStream errorStream = process.getErrorStream();

        readStream(inputStream);
        readStream(errorStream);

        return process.waitFor();

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

    return -1;
}

Then just pass in the List containing your python commands.

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