如何从Java执行Python脚本? [英] How to execute Python script from Java?
问题描述
我可以从Java执行Linux命令,如 ls
或 pwd
但没有问题,但无法获得Python脚本执行。
I can execute Linux commands like ls
or pwd
from Java without problems but couldn't get a Python script executed.
这是我的代码:
Process p;
try{
System.out.println("SEND");
String cmd = "/bash/bin -c echo password| python script.py '" + packet.toString() + "'";
//System.out.println(cmd);
p = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = br.readLine();
System.out.println(s);
System.out.println("Sent");
p.waitFor();
p.destroy();
} catch (Exception e) {}
什么都没发生。它达到SEND但它刚刚停止...
Nothing happened. It reached SEND but it just stopped after it...
我正在尝试执行一个需要root权限的脚本,因为它使用串口。另外,我必须传递带有一些参数(包)的字符串。
I am trying to execute a script which needs root permissions because it uses serial port. Also, I have to pass a string with some parameters (packet).
推荐答案
你不能在<$ c里面使用PIPE $ c> Runtime.getRuntime()。exec()就像在你的例子中一样。 PIPE是shell的一部分。
You cannot use the PIPE inside the Runtime.getRuntime().exec()
as you do in your example. PIPE is part of the shell.
你可以做任何一次
- 把你的命令shell脚本并使用
.exec()
或 -
执行该shell脚本您可以执行类似于以下
- Put your command to a shell script and execute that shell script with
.exec()
or You can do something similar to the following
String[] cmd = {
"/bin/bash",
"-c",
"echo password | python script.py '" + packet.toString() + "'"
};
Runtime.getRuntime().exec(cmd);
这篇关于如何从Java执行Python脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!