2013-05-08 162 views
10

我可以从Java执行Linux命令(如lspwd),但没有问题,但无法执行Python脚本。如何从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) {} 

什么也没发生。它达到了发送,但它只是在它之后停止...

我想执行一个需要root权限的脚本,因为它使用串行端口。此外,我必须传递一些参数(包)的字符串。

+0

是你的python脚本写出somethong它的标准? – VishalDevgire 2013-05-08 18:15:30

+0

如何使用Apache commons exec? – rkosegi 2013-05-08 18:20:15

回答

14

您不能像在示例中那样在Runtime.getRuntime().exec()内使用PIPE。 PIPE是shell的一部分。

你可以做任何

  • 把你的命令shell脚本并执行shell脚本.exec()
  • 你可以做类似下面的

    String[] cmd = { 
         "/bin/bash", 
         "-c", 
         "echo password | python script.py '" + packet.toString() + "'" 
        }; 
    Runtime.getRuntime().exec(cmd); 
    
+0

如何为此做一个shell脚本?我从来没有创建过shell脚本 – Biribu 2013-05-08 18:37:32

+2

即使没有创建shell脚本文件,这个答案也可以工作。只需将其复制粘贴到您的代码即可。 – pts 2013-05-08 18:43:50

+0

@pts是的,它的工作原理,但我无法解释清楚。我更新了这篇文章,我希望现在好一点。 – Alper 2013-05-08 19:19:15

12
东西

@Alper的答案应该可行。但更好的是,不要使用shell脚本和重定向。您可以使用(易名为)Process.getOutputStream()将密码直接写入进程stdin。

Process p = Runtime.exec(
    new String[]{"python", "script.py", packet.toString()}); 

BufferedWriter writer = new BufferedWriter(
    new OutputStreamWriter(p.getOutputStream())); 

writer.write("password"); 
writer.newLine(); 
writer.close(); 
+0

这是否将与Windows以及Linux一起使用? – 2017-04-29 19:40:54

+1

@ChinmayaB - 是的,这是操作系统不可知论者。 – jtahlborn 2017-04-29 19:48:49

7

你会做的比尝试embedding jython并执行你的脚本更糟糕。一个简单的例子应该有所帮助:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("python"); 

// Using the eval() method on the engine causes a direct 
// interpretataion and execution of the code string passed into it 
engine.eval("import sys"); 
engine.eval("print sys"); 

如果您需要更多帮助,请发表评论。这不会创建额外的过程。