如何从Java执行Python脚本?(How to execute Python script fr

2019-09-02 06:48发布

我能运行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) {}

没啥事儿。 它达到了发送,但之后它只是停止...

我试图执行一个脚本,需要root权限,因为它使用串行端口。 另外,我要通过一些参数(数据包)的字符串。

Answer 1:

你不能使用管道内部Runtime.getRuntime().exec()你在你的例子做。 管壳的一部分。

你可以做任何

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

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


Answer 2:

@阿尔珀的答案应该工作。 更重要的是,虽然没有在所有使用shell脚本和重定向。 您可以直接写密码进程的标准输入使用(容易混淆的名字命名) Process.getOutputStream()

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();


Answer 3:

你会做的不如尝试嵌入的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");

如果您需要进一步的帮助,发表评论。 这不会产生额外的过程。



文章来源: How to execute Python script from Java?