简体   繁体   English

使用runtime.getruntime.exec从Java调用python脚本

[英]Calling python script from Java using runtime.getruntime.exec

I have a java web development project, and want to call a python script to run in the background and then carry on with the java. 我有一个java web开发项目,想要调用python脚本在后台运行然后继续使用java。

String command = "cmd.exe /c cd "C:\\path\\to\\py\\" && python script.py";
Process p = Runtime.getRuntime().exec(command);

Nothing seems to happen when i call this, but i need to change directory first as the script accesses files in its directory. 当我调用它时似乎没有发生任何事情,但我需要首先更改目录,因为脚本访问其目录中的文件。

Thanks for your help 谢谢你的帮助

Edit: 编辑:

Correct answer was adding start, this is my edited code 正确的答案是添加开始,这是我编辑的代码

String command = "cmd.exe /c cd "C:\\path\\to\\py\\" && start python script.py";
Process p = Runtime.getRuntime().exec(command);

Rather than using cmd to change the directory, you can set a process's working directory from the Java side. 您可以从Java端设置进程的工作目录,而不是使用cmd来更改目录。 For example 例如

ProcessBuilder pb = new ProcessBuilder("python", "script.py");
pb.directory(new File("C:\\path\\to\\py"));
Process p = pb.start();

Did you configure your environment to support "executable" python scripts? 您是否将环境配置为支持“可执行”python脚本?
If not, you should call it like this: 如果没有,你应该这样称呼它:

String command = "cmd.exe /c start python path\to\script\script.py";
Process p = Runtime.getRuntime().exec(command);

The start command runs the appropriate executable (in this case python interpreter), with its supplied arguments (in this case the script itself). start命令使用其提供的参数(在本例中为脚本本身)运行相应的可执行文件(在本例中为python解释器)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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