How to execute Python script from Java?

后端 未结 4 767
一个人的身影
一个人的身影 2020-11-30 04:06

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:

相关标签:
4条回答
  • 2020-11-30 04:50

    First, open terminal and type "which python3". You will get the complete path of python3. For example "/usr/local/bin/python3"

    String[] cmd = {"/usr/local/bin/python3", "arg1", "arg2"};
    Process p = Runtime.getRuntime().exec(cmd);
    p.waitFor();
    
    String line = "", output = "";
    StringBuilder sb = new StringBuilder();
    
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    while ((line = br.readLine())!= null) {sb = sb.append(line).append("\n"); }
    
    output = sb.toString();
    System.out.println(output);
    
    0 讨论(0)
  • 2020-11-30 04:55

    @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();
    
    0 讨论(0)
  • 2020-11-30 04:57

    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.

    0 讨论(0)
  • 2020-11-30 05:07

    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);
      
    0 讨论(0)
提交回复
热议问题