开发者

Call python script within java code (runtime.exec)

I'm try开发者_运维技巧ing 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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜