How to execute Python script from Java (via command line)?

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

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

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.