【问题标题】:How to execute a python file with some arguments in java如何在java中执行带有一些参数的python文件
【发布时间】:2026-01-14 16:35:01
【问题描述】:
字符串命令:
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");
}
代码既不终止也不给出实际结果。 ...
【问题讨论】:
-
-
另请参阅When Runtime.exec() won't,了解有关正确创建和处理流程的许多好技巧。然后忽略它引用exec 并使用ProcessBuilder 创建进程。还将String arg 分解为String[] args 以解决包含空格字符的路径之类的问题。
标签:
java
python
devops
runtime.exec
【解决方案1】:
这可能会有所帮助!
您可以使用Java Runtime.exec() 来运行python 脚本,例如首先使用shebang 创建一个python 脚本文件,然后将其设置为可执行文件。 p>
#!/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();
}
}