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?

1
  • 2
    you'll need to provide more info. How are you executing python from your script? Can you show us a stackoverflow.com/help/mcve ? Commented Aug 13, 2018 at 0:28

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.