SpringBoot(Java)调用Python脚本及传参
概述
本文用一个简单的例子,描述如何在SpringBoot中调用Python脚本,并获取Python返回的参数
Java调用并传参
public void test() {
System.out.println("Start");
// python脚本的绝对路径,在windows中用"\\"分隔,在Linux中用"/"分隔
String pyPath = "E:\\Code\\Java\\myproject\\src\\main\\resources\\demo2.py";
// 传入python脚本的参数为”111“
String[] args1 = new String[]{"python", pyPath, "111"};
try {
// 执行Python文件,并传入参数
Process process = Runtime.getRuntime().exec(args1);
// 获取Python输出字符串作为输入流被Java读取
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String actionStr = in.readLine();
if (actionStr != null) {
System.out.println(actionStr);
}
in.close();
process.waitFor();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("End");
}
Python脚本接受参数并返回结果
import sys
if __name__ == '__main__':
stateStr = sys.argv[1];
number = int(stateStr) + 5;
print("Python return: " + str(number));
输出结果
Start
Python return: 116
End
参考文献
Java调用Python脚本传递数据并返回计算结果