注意:python.exe的路径已经设置
我正在尝试创建一个 Java 程序,将变量 args
(或任何其他变量)传递给 Python 脚本。
import java.io.*;
public class PythonCallTest{
public static void main (String[] args){
String s = null;
Runtime r = Runtime.getRuntime();
try{
Process p = r.exec("cmd /c python ps.py+",args);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
while ((s = stdInput.readLine()) != null){
System.out.println(s);
}
while ((s = stdError.readLine()) != null){
System.out.println(s);
}
System.exit(0);
}
catch(IOException ioe){
ioe.printStackTrace();
System.exit(-1);
}
}
}
程序可以编译,但是当我使用
运行它时java PythonCallTest sender-ip=10.10.10.10
我收到错误
'python' is not recognized as an internal or external command, operable program or batch file.
如何正确连接 r.exec("cmd/c python ps.py+",args) 中的字符串
编辑
如果我执行以下命令
Process p = r.exec("cmd /c python ps.py sender-ip=10.251.22.105");
然后程序就可以运行了。 python.exe 的路径已经设置。我只需要知道如何将 args 添加到 r.exec,即如何将 cmd/c python ps.py 与 args
连接起来最佳答案
您将 args
作为 Runtime.exec(...)
的第二个参数传递。
这会覆盖新进程的默认(继承)环境,使其变得无用,因此 Path
变量不再包含 python.exe
的路径。
您需要使用此版本的Runtime.exec(...)
:
public Process exec(String[] cmdarray);
你会这样做:
public static void main(String[] args) {
...
List<String> process_args = new ArrayList<String>(Arrays.asList("cmd", "/c", "python", "ps.py"));
process_args.addAll(Arrays.asList(args));
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec(process_args.toArray(new String[] {}));
...
} catch (IOException e) {
...
}
}
关于Java 将参数传递给 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24512412/