app
潘志宝
2024-08-19 2563526c3fda3ae9b45aad02ed10427508a29af3
提交 | 用户 | 时间
a6de49 1 package com.iailab.common.utils;
H 2
3 import com.alibaba.fastjson.JSONObject;
4 import lombok.extern.slf4j.Slf4j;
5
6 import java.io.BufferedReader;
7 import java.io.InputStreamReader;
8 import java.util.ArrayList;
9 import java.util.List;
10 import java.util.Map;
11
12 /**
13  * @author PanZhibao
14  * @Description
15  * @createTime 2023年01月11日 11:03:00
16  */
17 @Slf4j
18 public class PythonUtil {
19
20     public static Map<String, Object> execPy(String[] command) throws Exception {
21         List<String> lines = new ArrayList<>();
22         try {
23             Process proc = Runtime.getRuntime().exec(command);
24             BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), "GBK"));
25             String line = null;
26
27             while ((line = in.readLine()) != null) {
28                 log.info(line);
29                 lines.add(line);
30             }
31             // 0表示成功,1表示远程调用失败,2表示python脚本出错
32             int waitFor = proc.waitFor();
33             log.info("waitFor=" + waitFor);
34             if (waitFor == 1) {
35                 throw new Exception("远程调用失败");
36             } else if (waitFor == 2) {
37                 throw new Exception("python脚本出错");
38             } else if (waitFor == 9009) {
39                 throw new Exception("环境变量配置错误");
40             } else if (waitFor != 0) {
41                 throw new Exception("调用python失败");
42             }
43         } catch (Exception ex) {
44             log.error("运行python异常!command=" + command.toString());
45             throw ex;
46         }
47         return JSONObject.parseObject(lines.get(0));
48     }
49 }