java中调用python语句
参数说明:
command:python文件路径
num1,num2:传入.py的参数,可自由增添。需要在String[] cmdArr = new String[] {exe,command,num1,num2};中进行相应增改
代码:
java部分
package test1;
import java.io.*;
public class test1 {
public static void main(String[] args) throws IOException,InterruptedException {
String exe = "python";
String command = "D:\\add.py";
String num1 = "1";
String num2 = "2";
String[] cmdArr = new String[] {exe,command,num1,num2};
Process process = Runtime.getRuntime().exec(cmdArr);
InputStream is = process.getInputStream();
BufferedReader dis = new BufferedReader(new InputStreamReader(is));
String str = dis.readLine();
process.waitFor();
System.out.println(str);
}
}
测试用的.py文件
# coding=utf-8
from sys import argv
num1 = argv[1]
num2 = argv[2]
sum = int(num1) + int(num2)
print(sum)
运行效果:
其他备注:
1.BufferedReader dis = new BufferedReader(new InputStreamReader(is)); String str = dis.readLine();是jdk1.1以上的写法。1.1以下参考https://bbs.csdn.net/topics/340000334
2.备选项是jython,jython不支持python3及大部分科学计算类包