3

I want to run a python script called, for example foo. And I have the absoulute path, lets say: /Users/me/pythonscripts/

I have tried running:

String cmd="/Users/me/pythonscripts/"
String py="foo"
Runtime.getRuntime().exec("cd "+cmd);
Runtime.getRuntime().exec("python "+py+".py");

But that does run the python file.

Others
  • 2,876
  • 2
  • 30
  • 52
  • Check the following link : http://norwied.wordpress.com/2012/03/28/call-python-script-from-java-app/ – A.P.S Jan 13 '14 at 00:05
  • You might also look at [jython](http://www.jython.org) which will jun python scripts on the Java VM – mmmmmm Jan 13 '14 at 00:15

2 Answers2

6

Try using something more like...

Runtime.getRuntime().exec("python "+cmd + py + ".py");

Instead. Each exec is it's own process and multiple exec has no relationship to each other...

You should also consider using ProcessBuilder instead, as this provides you with a great level of configurability, for example, you can change the execution path context...

ProcessBuilder pb = new ProcessBuilder("python", py + ".py");
pb.directory(new File(cmd));
pb.redirectError();
//...
Process p = pb.start();

Also, beware, that Python has an issue with it's output stream, which may prevent Java from reading it until it's completely finished if at all...

For more details, take a look at Java: is there a way to run a system command and print the output during execution?

Also, make sure python is within the shell's search path, otherwise you will need to specify the full path to the command as well

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Thanks for the ProcessBuilder tip, super helpful! Works great now. – Others Jan 13 '14 at 00:02
  • It just didn't execute the python file, not sure what the issue was there. I commented a bit prematurely though, I made this work great with process builder. – Others Jan 13 '14 at 00:05
1

this work for me

    public static void main(String[] args)  throws IOException{

    Runtime runtime = Runtime.getRuntime();
    Process p1 = runtime.exec("D:\\programs\\Anaconda3\\Scripts\\spyder.exe \"C:\\Users\\Al-Hanouf\\codes\\PageRank.py\"");
    System.out.print("is process alive = "+p1.isAlive());

}