如何在java中执行带有一些参数的python文件

Sha*_*kir -1 python java runtime.exec devops

字符串命令:

python FileName.py <ServerName> userName pswd<b>
Run Code Online (Sandbox Code Playgroud)
Process p = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
    System.out.println(line + "\n");
}
Run Code Online (Sandbox Code Playgroud)

代码既不终止也不给出实际结果。...

Sha*_*Ali 5

这可能会有帮助!

您可以使用 Java Runtime.exec()来运行 python 脚本,作为示例,首先使用shebang创建一个 python 脚本文件,然后将其设置为可执行文件。

#!/usr/bin/python
import sys
print 'Number of Arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.arv)
print('This is Python Code')
print('Executing Python')
print('From Java')
Run Code Online (Sandbox Code Playgroud)

如果将上述文件保存为 script_python 然后使用设置执行权限

chmod 777 script_python
Run Code Online (Sandbox Code Playgroud)

然后你可以从 Java Runtime.exec()调用这个脚本,如下所示

import java.io.*;
import java.nio.charset.StandardCharsets;

public class ScriptPython {
       Process mProcess;

public void runScript(){
       Process process;
       try{
             process = Runtime.getRuntime().exec(new String[]{"script_python","arg1","arg2"});
             mProcess = process;
       }catch(Exception e) {
          System.out.println("Exception Raised" + e.toString());
       }
       InputStream stdout = mProcess.getInputStream();
       BufferedReader reader = new BufferedReader(new InputStreamReader(stdout,StandardCharsets.UTF_8));
       String line;
       try{
          while((line = reader.readLine()) != null){
               System.out.println("stdout: "+ line);
          }
       }catch(IOException e){
             System.out.println("Exception in reading output"+ e.toString());
       }
}
}

class Solution {
      public static void main(String[] args){
          ScriptPython scriptPython = new ScriptPython();
          scriptPython.runScript();
      }

}
Run Code Online (Sandbox Code Playgroud)