如何在java中使用一些参数执行python文件
字符串命令:如何在java中使用一些参数执行python文件,java,python,devops,runtime.exec,Java,Python,Devops,Runtime.exec,字符串命令: python FileName.py <ServerName> userName pswd<b> 代码既没有终止也没有给出实际结果 这可能会有帮助 您可以使用Java Runtime.exec()运行python脚本,例如,首先使用shebang创建一个python脚本文件,然后将其设置为可执行文件 #!/usr/bin/python import sys print 'Number of Arguments:', len(sys.argv), 'argu
python FileName.py <ServerName> userName pswd<b>
代码既没有终止也没有给出实际结果 这可能会有帮助强> 您可以使用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();
}
}
看看这里,也可以看到许多正确创建和处理流程的好技巧。然后忽略它引用exec
,并使用ProcessBuilder
创建流程。还可以将字符串arg
分解为字符串[]args
,以说明包含空格字符的路径之类的情况。
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();
}
}