小编典典

如何从Java执行Python脚本?

linux

我能运行Linux命令状lspwd从Java没有问题,但不能得到执行的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权限的脚本,因为它使用串行端口。另外,我还必须传递带有一些参数的字符串(数据包)。


阅读 1034

收藏
2020-06-02

共1个答案

小编典典

您不能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);
2020-06-02