0

I'm attempting to run a Python script using Java code in Intellij IDEA:

String commandString = "python /home/.../mypythonscript.py arg1 arg2";
try {
    Process process = Runtime.getRuntime().exec(commandString);
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
} catch(IOException e) {
    System.out.println(e.getMessage());

The Python script outputs a single String, and works great when I run it from my Ubuntu Linux terminal. However, using the above Java to run the Python script returns an error message:

Failed to run Python Script: Cannot run program "python": error=2, No such file or directory.

The file path is correct (the path and arguments I give are identical to what I used to run the Python script in the terminal), and I've set the script permissions to 777. In Intellij, I've also gone to File>Settings>Appearance & Behavior>Path Variables and added a path to the folder that contains the Python script (it's being held in a folder for Pycharm projects). However, I'm still getting the error.

Any help would be much appreciated!

wb1210
  • 50
  • 8
  • What OS do you use? Terminal environment can be different from the environment visible to the UI apps, see https://stackoverflow.com/a/26586170/104891. You can type `env` in the Terminal tool window in IntelliJ IDEA to print the variables and double check that `python` binary is in `PATH`. – CrazyCoder Aug 16 '20 at 23:42
  • I'm using an Ubuntu virtual machine (by terminal, I mean the Ubuntu terminal, not the terminal in Intellij). In reference to my previous comment, which I've now deleted, I updated python to python3. Using process.waitFor(), I realized that the script is not running, or is encountering an error when it runs, so the issue persists, though it no longer shows an error. – wb1210 Aug 17 '20 at 16:02
  • If there is no error shown, then the issue is completely different. Please share the [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) including the Python script that you are trying to run from Java code. – CrazyCoder Aug 17 '20 at 17:31
  • @CrazyCoder, that's a good point-- thanks. I've rolled back the question to its previous version, to assist others with a similar issue. – wb1210 Aug 18 '20 at 14:32

1 Answers1

0

A more experienced Java developer friend of mine who doesn't have an account figured out the problem, the solution to which I'm posting here for anyone encountering a similar issue in the future:

The script was written in Python3, but the code I used:

String commandString = "python /home/.../mypythonscript.py arg1 arg2";

is for Python 2. It should have been written:

String commandString = "python3 /home/.../mypythonscript.py arg1 arg2";
wb1210
  • 50
  • 8