private static String os = System.getProperty("os.name").toLowerCase();//获取当前操作系统类型
private String uploadPath;//系统附件文件路径,如:/home/uploadPath
/**
* 执行python脚本,利用JVM的Runtime.getRuntime()实例直接执行脚本,相当于在系统控制台直接执行python脚本,例如在系统控制台执行:python test.py
* 需要注意:python脚本中如果有文件的操作等,需要填写文件的绝对路径,例如:with open('/opt/upFiles/script/python/cjfx/save/svm.pickle', 'rb') as f:
* @param name 要执行的脚本名称,例如:test.py
* @param data 参数,可为空,例如:--data -0.50700939 0.53240926 0.41433287 1.05468259 1.69092982 -1.39385769 -1.4536529 -0.63040027
* @return
*/
public Result<?> execPython(String name, String data) {
String result = null;
Process proc;
try {
//拼接执行脚本,例如:python /opt/upFiles/script/python/cjfx/pred.py --data -0.50700939 0.53240926 0.41433287 1.05468259 1.69092982 -1.39385769 -1.4536529 -0.63040027
String script = "python " + uploadPath + File.separator + "script" + File.separator + "python" + File.separator + "cjfx" + File.separator + name + " " + data;
log.info(script);
proc = Runtime.getRuntime().exec(script);//执行脚本命令
//windows的控制台与Linux编码不同,为避免中文乱码问题,BufferedReader根据操作系统类型不同进行不同的解码
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), os.indexOf("windows") >= 0 ? "gbk" : "utf-8"));//获取脚本输出结果
BufferedReader isError = new BufferedReader(new InputStreamReader(proc.getErrorStream(), os.indexOf("windows") >= 0 ? "gbk" : "utf-8"));//获取执行错误结果
String line;
while ((line = in.readLine()) != null) {
result = line;
log.info(line);
}
if (StrUtil.isBlank(result)) {//如果脚本输出结果为空,则打印执行错误信息
while ((line = isError.readLine()) != null) {
result = line;
log.info(line);
}
}
int res = proc.waitFor();
in.close();
isError.close();
log.info("================= 脚本执行结果:{} =================", res);//res在等于0时为正确执行
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return Result.OK(result);
}