由于项目需要,需要用java调用python脚本,网上有很多代码例子,但前提要求是使用默认的python版本,java文件跟脚本要在同一目录。
这无法满足要求
如果是使用默认的python环境
在这里,参数str是脚本的位置,我将调用python脚本的方法单独出来。(注意注释)package com.issac.until;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class RunPython {
public static int callPython(String str){
int re = 0;
String[] arguments = new String[] {"python", str};
try {
Process process = Runtime.getRuntime().exec(arguments);
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
//java代码中的process.waitFor()返回值为0表示我们调用python脚本成功,
//返回值为re == 1表示调用python脚本失败,这和我们通常意义上见到的0与1定义正好相反
re = process.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
return re;
}
}
然后在controller,或者是main里面,直接调用。例如这样子,控制台会输出脚本打印出来的东西,最后会返回0或者1。
callPython("E://faster-rcnn-keras-master//VOCdevkit//VOC2007//one.py");
callPython("E://faster-rcnn-keras-master//two.py");
如果是使用python虚拟环境
callPython里面的“python”(这里指的是使用默认的python环境),试过直接改“python”改成虚拟环境目录的python.exe那个路径,不过好像无效 这里采取了另外一种方法,将虚拟环境的环境配置移到最上面代码还是原来那个代码,就可以运行了。
如果有其他方法,请指点一二。