我可以毫无问题地从 Java 执行 ls
或 pwd
等 Linux 命令,但无法执行 Python 脚本。
这是我的代码:
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,但在它之后就停止了...
我正在尝试执行一个需要root权限的脚本,因为它使用串行端口。另外,我必须传递一个带有一些参数(数据包)的字符串。
最佳答案
您不能像示例中那样在 Runtime.getRuntime().exec()
中使用 PIPE。 PIPE 是 shell 的一部分。
你可以做任何一个
- 将命令放入 shell 脚本并使用
.exec()
或 执行该 shell 脚本
您可以执行类似于以下的操作
String[] cmd = { "/bin/bash", "-c", "echo password | python script.py '" + packet.toString() + "'" }; Runtime.getRuntime().exec(cmd);
关于java - 如何从 Java 执行 Python 脚本(通过命令行)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33981742/