如何从Java执行Python脚本?

Bir*_*ibu 11 python java 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) {}
Run Code Online (Sandbox Code Playgroud)

没啥事儿.它达到SEND但它刚刚停止......

我正在尝试执行需要root权限的脚本,因为它使用串行端口.另外,我必须传递带有一些参数(包)的字符串.

Alp*_*per 18

您不能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);
    
    Run Code Online (Sandbox Code Playgroud)

  • 即使没有创建shell脚本文件,这个答案仍然有效.只需将其复制粘贴到您的代码中即可. (2认同)

jta*_*orn 12

@Alper的答案应该有效.但更好的是,根本不使用shell脚本和重定向.您可以使用(容易混淆的名称)将密码直接写入进程'stdin 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();
Run Code Online (Sandbox Code Playgroud)


hd1*_*hd1 7

你会比尝试嵌入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");
Run Code Online (Sandbox Code Playgroud)

如果您需要进一步的帮助,请发表评论.这不会创建额外的过程.