Java调用Python代码
比较优秀的一篇博客可参考
https://blog.csdn.net/qq_40507857/article/details/120041897
在项目中使用过的如下:
import java.io.*;
import java.util.concurrent.TimeUnit;
public class RuntimeFunction {
public static void main(String[] args) throws IOException, InterruptedException {
// String exe = "python";
// // 路径
// String command = "C:\\Users\\Desktop\\test.py";
// 形参(可以不需要)
// String num1 = "1";
// String num2 = "2";
// String[] cmdArr = new String[]{exe, command, num1, num2};
String[] args1 = new String[]{"python","E:\\distinguishSerumTraits_calVolume.py"};
// String args = "D:\\python3.7\\python.exe C:\\Users\\Desktop\\Tube\\test.py";
// 调用Runtime处理数组数据,调用进程
Process process = Runtime.getRuntime().exec(args1);
// InputStream is = process.getInputStream();
// DataInputStream dis = new DataInputStream(is);
// BufferedReader d = new BufferedReader(new InputStreamReader(dis));
BufferedReader d = new BufferedReader(new InputStreamReader(process.getInputStream()));
// 如有必要,使当前线程等待,直到此进程对象表示的进程终止。如果子流程已终止,则此方法立即返回。如果子进程尚未终止,调用线程将被阻塞,直到子进程退出。
// process.waitFor(12,TimeUnit.MINUTES);
// Thread.sleep(1000);
System.out.println(d.readLine());
d.close();
process.waitFor();
}
}
// 要注意,Python文件中的路径必修为绝对路径