Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call python script within java code (runtime.exec)

I'm trying to run a python script in java but I'm having some troubles. I'm using the command bellow to execute the python script which is inside a folder called python in my java project:

Runtime r = Runtime.getRuntime();
Process p = r.exec("cmd /c python python\\test.py");

The script should write something in a text file and on the screen, but after the execution throught r.exec, this doesn't work (nothing is recorded neither written on the screen and p.waitFor() returns 1, meaning it didn't work properly), it works in terminal though. I tried to place the python script in the root folder of the project to see if the error could have been caused by some path mistake but I had no success either. How can I get this to work?

My SO is Windows 7 and the python script (test.py) I'm trying to run is:

import sys
import os

def main():
    f = open('python/test.txt','w')
    f.write('It works!')
    f.flush()
    f.close()
    print('It works!')

if __name__ == '__main__':
    main()
like image 814
Paulo Avatar asked Feb 22 '23 23:02

Paulo


1 Answers

Most likely the python executable is not in the path that's given to the child process. Try changing the command line to include the full path to the python executable, as in

Process p = r.exec("cmd /c c:\\path\\to\\python python\\test.py");
like image 188
Jim Garrison Avatar answered Feb 25 '23 15:02

Jim Garrison