[DEBUG] java中用Runtime调用python 简单程序输出null

2023-03-02,,,,

今天需要在java中调用python脚本,首先考虑的是java自带的Runtime

在ubuntu和win10下分别测试,发现win10报错

java源代码

@Test
public void testRuntime() throws InterruptedException {
Scanner input = new Scanner(System.in); // 在同一行输入两个数字,用空格分开,作为传入Python代码的命令行参数
System.out.println("Enter two integers(e.g. 12 34): ");
String integers = input.nextLine();
String[] numbers = integers.split(" "); // 定义传入Python脚本的命令行参数,将参数放入字符串数组里
String cmds = String.format("python F:\\eclipse\\springboot2\\demo\\src\\test\\java\\com\\example\\demo\\cal.py %s %s", numbers[0], numbers[1]); // 执行CMD命令
System.out.println("\nExecuting python script file now.");
Process pcs;
try {
pcs = Runtime.getRuntime().exec(cmds);
pcs.waitFor(); // 定义Python脚本的返回值
String result = null;
// 获取CMD的返回流
BufferedInputStream in = new BufferedInputStream(pcs.getInputStream());
// 字符流转换字节流
BufferedReader br = new BufferedReader(new InputStreamReader(in));
// 这里也可以输出文本日志 String lineStr = null;
while ((lineStr = br.readLine()) != null) {
result = lineStr;
}
// 关闭输入流
br.close();
in.close(); System.out.println(result);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }

python源代码

#coding=utf-8
from sys import argv num1 = argv[1]
num2 = argv[2]
sum = int(num1) + int(num2)
print sum

ubuntu下正确输出

报错原因:

win10我装的是python3,ubuntu下是python2,所以python2支持的格式,在python3下是不行的:)

修改cal.py

print(sum)

这样就可以兼容Python2和3了。修改之后正确输出

[DEBUG] java中用Runtime调用python 简单程序输出null的相关教程结束。