Java程序通过命令行形式调用Python脚本
主函数可以这样写 代码片
.
//写调用python脚本的cmd 例如python main.py -f filename
public static void main(String[]args){
String cmd = "python main.py";
String results = algorithm(cmd);
System.out.println(results);
}
ps:保证在命令行窗口下可以执行编辑的cmd;
下面展示调用函数的 代码片
.
// 调用脚本函数
public static String algorithm(String cmd) {
Process process;
try {
process = Runtime.getRuntime().exec(cmd);
process.waitFor();
String inStr = consumeInputStream(process.getInputStream());
String errStr = consumeInputStream(process.getErrorStream());
return inStr;
} catch (Exception e) {
return "";
}
};
下面展示consumeInputStream函数的 代码片
.
// 返回脚本执行结果
private static String consumeInputStream(InputStream inputStream) throws IOException {
BufferedReader inBuffer = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder output = new StringBuilder();
String line = null;
while ((line = inBuffer.readLine()) != null) {
output.append(line);
}
inBuffer.close();
return output.toString();
}
Python程序调用命令行
主函数可以这样写 代码片
.
//写调用python脚本的cmd 例如python main.py -f filename
import subprocess
def main():
cmd = 'python main.py'
p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
//保存结果
p.wait()
result_lines = p.stdout.readlines() # 从子进程 p 的标准输出中读取所有行,并储存在一个list对象中
for line in result_lines:
print(line.strip())