How to execute Python script from Java?

后端 未结 4 788
一个人的身影
一个人的身影 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: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();
    

提交回复
热议问题