1.到官网下载python3下载很慢。安装PYTHON3.xx包到本地。
2.pom文件引入
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.1</version>
</dependency>
3.调用方式:
//PYTHON脚本执行命令
private static final String PY_COMMAND="python";
/**
* rootPath 预测模型文件夹根路径
* pyName PY文件名称
* jsonParam JSON格式的入参
* operFlag 操作标识 1 训练模型 2预测
*/
public static String getPyResult(String pyName, String jsonParam,String operFlag) {
//存放py文件夹的根目录
String rootPath = CsvCreateUtils.getPreRootPath();
//执行的PY脚本
final String pyPath = rootPath + pyName;
boolean checkFlag = checkPySetParam(pyName, rootPath, pyPath);
if(!checkFlag) {
return null;
}
StringBuffer returnStr = new StringBuffer();
try {
//入参可传json格式的字符,在python 文件中可以sys.argv[1]获取
String jsonFile = "";
// 执行PY文件
logger.info("py文件执行start");
String[] args = new String[] {PY_COMMAND,pyPath,jsonFile}; //设定命令行
Process proc = Runtime.getRuntime().exec(args); //执行PY文件
logger.info("py文件执行end");
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(),Charset.forName("UTF-8")));
String line = null;
while ((line = in.readLine()) != null) {
returnStr.append(line);
}
in.close();
proc.waitFor();
} catch (IOException | InterruptedException e1) {
e1.printStackTrace();
logger.info(e1.getStackTrace().toString());
logger.info(e1.getMessage());
}
return returnStr.toString();
}
/**
* 验证运行环境
*/
public static boolean checkPySetParam(String pyName,String homePath,String pyPath) {
boolean flag = true;
Path pathToDirectory = Paths.get(homePath);
if (!Files.exists(pathToDirectory)) {
flag =false;
logger.info("存放py文件的文件夹不存在,请检查该路径是否存在:" + homePath);
return flag;
}
pathToDirectory = Paths.get(pyPath);
if (!Files.exists(pathToDirectory)) {
flag =false;
logger.info("py文件不存在,请检查该路径是否存在:" + pyPath);
return flag;
}
return flag;
}