Java调用python脚本
1.java调用python脚本需要运行python的基本环境
2.Process process = Runtime.getRuntime().exec(cmdArr);
在java代码中使用上述代码调用python脚本即可,其中cmdArr相当于在cmd
调用python脚本时的指令。
3.其原理是建立一个新的进程来运行python代码。
4.cmdArr是以字符串数组的形式。
实例代码
public static void main(String[] args) throws IOException, InterruptedException {
//pychon的环境路径
String exe = "python ";
// 存储pychon脚本的存储路径
String command = "F:\\YOLOv4-Hat-detection-master\\detect.py";
// 定义传入Python脚本的命令行参数,将参数放入字符串数组里
String num1 = "--source 1.mp4";
String num2 = "--number camera1";
String[] cmdArr = new String[] {exe, command};
//使用Runtime.getRuntime()方法去调用pychon程序
Process process = Runtime.getRuntime().exec(cmdArr);
//取得命令结果的输出流
InputStream is = process.getInputStream();
//声明输出流对象,将结果显示出来
DataInputStream dis = new DataInputStream(is);
String str = dis.readLine();
System.out.println(str);
System.out.println(process.waitFor());
}