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()
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With