字符串命令:
python FileName.py <ServerName> userName pswd<b>
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");
}
代码既不会终止也不会给出实际结果。 ...
答案 0 :(得分:2)
这可能会有帮助!
您可以使用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')
如果将上述文件保存为script_python,然后使用
设置执行权限chmod 777 script_python
然后你可以从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();
}
}