简体   繁体   中英

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()

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM