1

I use the following lines of code to run a python script:

    Runtime rt = Runtime.getRuntime();  
    String command = PYTHON + " " + "foo.py";
    try {
        System.out.println("Python Command: " + command);
        rt.exec(command);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Previously it was enough to set PYTHON ="python"; however after setting up Anaconda3 again, this did no longer work, though entering above command via command line did work.

Java threw the following error code: java.io.IOException: Cannot run program "python": CreateProcess error=2, The system cannot find the file specified

However I found out, that Java was completely happy, if I gave it the full path to the python.exe inside Anaconda3 and everything worked magically.

This got me curious now, how Runetime.exec really works, when and how environment variables are used/accepted properly as I find the just described behaviour rather strange.

As always any constructive comment/answer makes me happy.

There are also other users on stackoverflow, who had the same problem, however no conclusive answers were provided. I refer to.

Run Python script from java code

Call and receive output from Python script in Java?

Imago
  • 521
  • 6
  • 29
  • Is `python` on your path? (Or at least, the path that you invoked Java with?) – Oliver Charlesworth Nov 12 '17 at 19:16
  • As stated: python is in my environmental variables(was before!) , now my Java code PYTHON include the full path to the python.exe. Is this what you were referring to? – Imago Nov 12 '17 at 19:27
  • Remember to use double-backslashes in that case. e.g. ```String PYTHON="c:\\program files\\python\\python.exe"``` or something like that. But, in fact, the error message says ```Cannot run program "python"```, without any path, so check again what you are doing. – tevemadar Nov 13 '17 at 00:30
  • *"How does Runtime.exec work?"* It works quite well, if used carefully. On that subject, I always recommend people implement ***every suggestion*** in an article linked in this, one of my 'copy/paste comments'. So.. See also [When Runtime.exec() won't](http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html) for many good tips on creating and handling a process correctly. Then ignore it refers to `exec` and use a `ProcessBuilder` to create the process. Also break a `String arg` into `String[] args` to account for things like paths containing space characters. – Andrew Thompson Nov 13 '17 at 01:44

0 Answers0