Java调用python程序

Java调用python程序,第1张

Java调用python程序

JavaPythonUtils

public class JavaPythonUtils {


    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");


    public static String cmd(String commandStr,String path) throws IOException {

        String result = null;
        Process ps = null;
        BufferedReader br = null;

        try {
            String osName = System.getProperty("os.name");
            if (osName != null) {
                if (osName.contains("Mac")) {
                    log.info("最终调用linux命令--[{}]", sdf.format(new Date()) + ":" + commandStr);
                    String[] cmd = new String[]{"/bin/sh", "-c", commandStr};
                    ps = Runtime.getRuntime().exec(cmd);
                    br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
                    StringBuffer sb = new StringBuffer();
                    String line;
                    while ((line = br.readLine()) != null) {
                        log.info("进入结果判断了吗--[{}]", line);
                        //执行结果加上回车
                        sb.append(line).append("n");
                    }
                    result = sb.toString();
                } else if (osName.contains("Windows")) {
                    File filePath = new File(path);
                    log.info("最终调用Windows命令--[{}]", sdf.format(new Date()) + " 命令:" + commandStr);
                    ps = Runtime.getRuntime().exec(commandStr, null, filePath);
                    br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        //log.info("进入结果判断了吗--[{}]", line);
                        //执行结果加上回车
                        sb.append(line).append("n");
                    }
                    result = sb.toString();
                } else {
                    log.error("系统出错..");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                br.close();
            }
            if (ps != null) {
                ps.destroy();
            }
        }
        log.info("最终结果-{}", result);
        return result;

    }

}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4670642.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-06
下一篇2022-11-06

发表评论

登录后才能评论

评论列表(0条)

    保存