1

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?

Benjy Strauss
  • 99
  • 1
  • 5
  • 2
    you'll need to provide more info. How are you executing python from your script? Can you show us a https://stackoverflow.com/help/mcve ? – erik258 Aug 13 '18 at 00:28

2 Answers2

3

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.

Alex Taylor
  • 8,343
  • 4
  • 25
  • 40
2

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.

Chris
  • 3,437
  • 6
  • 40
  • 73