windows 在 java 代码中调用 python 脚本 (runtime.exec)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7449395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 18:06:17  来源:igfitidea点击:

Call python script within java code (runtime.exec)

javapythonwindowsruntime.exec

提问by Paulo

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:

我正在尝试在 java 中运行 python 脚本,但遇到了一些麻烦。我正在使用下面的命令来执行我的 java 项目中名为 python 的文件夹内的 python 脚本:

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?

脚本应该在文本文件和屏幕上写一些东西,但是在通过 r.exec 执行之后,这不起作用(没有记录也没有写在屏幕上并且 p.waitFor() 返回 1,这意味着它没有) t 正常工作),但它在终端中工作。我试图将 python 脚本放在项目的根文件夹中,看看错误是否可能是由某些路径错误引起的,但我也没有成功。我怎样才能让它工作?

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

我的 SO 是 Windows 7,我尝试运行的 python 脚本 (test.py) 是:

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

回答by Jim Garrison

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

很可能 python 可执行文件不在提供给子进程的路径中。尝试更改命令行以包含 python 可执行文件的完整路径,如

Process p = r.exec("cmd /c c:\path\to\python python\test.py");