How to execute Python script from Java?

2019-01-07 12:37发布

问题:

I can execute Linux commands like ls or pwd from Java without problems but couldn't get a Python script executed.

This is my code:

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) {}

Nothing happened. It reached SEND but it just stopped after it...

I am trying to execute a script which needs root permissions because it uses serial port. Also, I have to pass a string with some parameters (packet).

回答1:

You cannot use the PIPE inside the Runtime.getRuntime().exec() as you do in your example. PIPE is part of the shell.

You could do either

  • Put your command to a shell script and execute that shell script with .exec() or
  • You can do something similar to the following

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


回答2:

@Alper's answer should work. Better yet, though, don't use a shell script and redirection at all. You can write the password directly to the process' stdin using the (confusingly named) 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();


回答3:

You would do worse than to try embedding jython and executing your script. A simple example should help:

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

If you need further help, leave a comment. This does not create an additional process.