如何使用j中的参数执行python文件

2024-03-29 00:19:32 发布

您现在位置:Python中文网/ 问答频道 /正文

字符串命令:

python FileName.py <ServerName> userName pswd<b>

^{pr2}$

代码既没有终止也没有给出实际结果。。。在


Tags: 字符串代码py命令usernamefilenamepswdservername
1条回答
网友
1楼 · 发布于 2024-03-29 00:19:32

这可能会有帮助!

您可以使用Java运行时.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')

如果您将上述文件另存为script_python,然后使用

^{pr2}$

然后您可以从Java调用这个脚本运行时.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();
      }

}

相关问题 更多 >