java中調(diào)用python語(yǔ)句
參數(shù)說(shuō)明:
command:python文件路徑
num1,num2:傳入.py的參數(shù),可自由增添。需要在String[] cmdArr = new String[] {exe,command,num1,num2};中進(jìn)行相應(yīng)增改
代碼:
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);
}
}
測(cè)試用的.py文件
# coding=utf-8
from sys import argv
num1 = argv[1]
num2 = argv[2]
sum = int(num1) + int(num2)
print(sum)
運(yùn)行效果:

圖片.png
其他備注:
1.BufferedReader dis = new BufferedReader(new InputStreamReader(is)); String str = dis.readLine();是jdk1.1以上的寫(xiě)法。1.1以下參考https://bbs.csdn.net/topics/340000334
2.備選項(xiàng)是jython,jython不支持python3及大部分科學(xué)計(jì)算類包