How to execute Python script from Java?

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

提交回复
热议问题