Invoke Python script in Java code (runtime.exec)
•
Java
I tried to run Python scripts in Java, but I ran into some trouble
Runtime r = Runtime.getRuntime(); Process p = r.exec("cmd /c python python\\test.py");
The script should write something in the text file and on the screen, but after execution through r.exec, it doesn't work (no content is recorded, neither is written on the screen, p.waitfor() returns 1, which means it doesn't work normally), although it works on the terminal I tried to put the python script in the root folder of the project to see if the error might be caused by some path error, but I didn't succeed How can I make it work?
My so is Windows 7. The python script (test. Py) I tried 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()
Solution
Most likely, the python executable is not in the path given to the child process Try changing the command line to include the full path of the python executable, such as
Process p = r.exec("cmd /c c:\\path\\to\\python python\\test.py");
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码