本文介绍了如何使用绝对路径从Java运行Python文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行一个名为foo的python脚本。我有absoulute路径,让我们说:
/ Users / me / pythonscripts /

I want to run a python script called, for example foo. And I have the absoulute path, lets say: /Users/me/pythonscripts/

我试过跑:

String cmd="/Users/me/pythonscripts/"
String py="foo"
Runtime.getRuntime().exec("cd "+cmd);
Runtime.getRuntime().exec("python "+py+".py");

但这确实运行了python文件。

But that does run the python file.

推荐答案

尝试使用更像......

Try using something more like...

Runtime.getRuntime().exec("python "+cmd + py + ".py");

相反。每个 exec 是它自己的进程,多个 exec 彼此没有任何关系......

Instead. Each exec is it's own process and multiple exec has no relationship to each other...

您还应该考虑使用 ProcessBuilder ,因为这为您提供了很高的可配置性,例如,您可以更改执行路径context ...

You should also consider using ProcessBuilder instead, as this provides you with a great level of configurability, for example, you can change the execution path context...

ProcessBuilder pb = new ProcessBuilder("python", py + ".py");
pb.directory(new File(cmd));
pb.redirectError();
//...
Process p = pb.start();

另外,请注意,Python的输出流存在问题,这可能会阻止Java读取它直到它完全结束,如果... ...

Also, beware, that Python has an issue with it's output stream, which may prevent Java from reading it until it's completely finished if at all...

有关详细信息,请查看

For more details, take a look at Java: is there a way to run a system command and print the output during execution?

另外,确保 python 在shell的搜索路径中,否则您还需要指定命令的完整路径

Also, make sure python is within the shell's search path, otherwise you will need to specify the full path to the command as well

这篇关于如何使用绝对路径从Java运行Python文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 01:23