• java 调用 python 脚本


    有时候在java项目里,需要执行Python脚本以下几种方式:
    
    1、直接执行Python脚本代码 
    引用 org.python包  创建一个 python解释器,貌似这种方式不可以导入第三方库,模块。。。
    
    PythonInterpreter interpreter = new PythonInterpreter();  
    interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");   ///执行python脚本12
    
    2 、执行python .py文件
    PythonInterpreter interpreter = new PythonInterpreter();  
    InputStream filepy = new FileInputStream("D:\demo.py"); 
    interpreter.execfile(filepy);  ///执行python py文件
    filepy.close();1234
    
    3、使用Runtime.getRuntime()执行脚本文件
        这种方式和.net下面调用cmd执行命令的方式类似。如果执行的python脚本有引用第三方包的,建议使用此种方式。使用上面两种方式会报错java ImportError: No module named arcpy。
      
    Process proc = Runtime.getRuntime().exec("python  D:\demo.py");  
    proc.waitFor();  
    

    项目webservice RESTful 风格 采用 sprintboot + jetty 内置容器打包 jar 方式运行 (持久层整合 mybatis)

    因为当前公司项目我要负责编写 webservice 部分代码,而我们后台是采用 python 做 AI model,所以,避免不了要java与python交互传递数据,此外客户要求直接返回数据

    仓促博客记录代码如下

    定义调用python service 接口

    public interface JPythonService {
        String callPythonScript(String pyFile,String params)throws Exception;
    }
    

    接口实现类

    
    import com.middleplugin.exception.CustomException;
    import java.io.BufferedInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.concurrent.ConcurrentHashMap;
    import com.middleplugin.service.JPythonService;
    import com.middleplugin.utils.DBUtil;
    import org.springframework.stereotype.Service;
    import org.apache.log4j.Logger;
    @Service
    public class JPythonServiceImpl implements JPythonService{
        private Logger logger = Logger.getLogger(JPythonServiceImpl.class);
        @Override
        public String callPythonScript(String pyFile,String params) throws IOException{
            Process process = null;
            try{
                String[] command = new String[]{"sh", "-c","/home2/xxx/anaconda/envs/py35/bin/python "+pyFile+" '"+params+"'"};
                process = Runtime.getRuntime().exec(command);
                for(String s:command){
                    System.out.print(s);
                }
                for(int i=0;i<=3;i++) {
                    System.out.println();
                }
    
            }
            catch(IOException e){
    //            e.printStackTrace();
    
                logger.error(e);
                throw e;
            }
            StringBuffer stringBuffer = new StringBuffer();
            InputStream stdIns = process.getInputStream();
            InputStream stdErrorIns= process.getErrorStream();
    
            BufferedInputStream stdInput = new BufferedInputStream(stdIns);
            BufferedInputStream stdError = new BufferedInputStream(stdErrorIns);
    
            ConcurrentHashMap<String,String> concurrentHashMap = new ConcurrentHashMap<String,String>();
    
            new Thread(){//读取标准输入流
                @Override
                public void run() {
                    int bytesRead = 0;
                    byte[] buffer=new byte[1024];
                    try {
                        while ((bytesRead = stdInput.read(buffer)) != -1) {
                            String chunk = new String(buffer,0,bytesRead);
                            stringBuffer.append(chunk);
                            concurrentHashMap.put("stdInput",chunk);
                            System.out.println("result: "+stringBuffer.toString());
                        }
                    }
                    catch(IOException ioe){
                        ioe.printStackTrace();
                    }
                    finally{
                        if(stdInput!=null){
                            try{stdInput.close();}
                            catch(IOException ioe){
                                ioe.printStackTrace();
                            }}
                    }
                }
            }.start();
    
            new Thread(){//读取标准错误流
                @Override
                public void run() {
                    int bytesRead = 0;
                    byte[] buffer=new byte[1024];
                    try {
                        while ((bytesRead = stdError.read(buffer)) != -1) {
                            String chunk = new String(buffer,0,bytesRead);
                            stringBuffer.append(chunk);
                            concurrentHashMap.put("stdError",chunk);
                            System.out.println("result: "+stringBuffer.toString());
                        }
                    }
                    catch(IOException ioe){
                        ioe.printStackTrace();
                    }
                }
            }.start();
    
            try {
                process.waitFor();
                process.destroy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (concurrentHashMap.get("stdError")!=null){
                throw new CustomException("python 脚本有问题!");
    //            DBUtil.insert_log();
            }
            return concurrentHashMap.get("stdInput");
        }
    }
    
    

    controller 层调用

    @Autowired
        private JPythonService jPythonService;
    
    @RequestMapping("/mtb/pyml")
        public JSONObject mtbML(@RequestBody JSONObject params){
            TriggerTaskServiceForMTBImpl  triggerTaskServiceForMTB = new TriggerTaskServiceForMTBImpl();
            JSONObject retJson = new JSONObject();
            String errorMessage = "success";
            Integer state = 200;
            String result = null;
            String treatmentRankingPyFile = config.getString("treatmentranking.file");
            try{ result = jPythonService.callPythonScript(treatmentRankingPyFile,params.toString());
            }
            catch(Exception e){
                errorMessage = e+" failed";
                state = 500;
                System.out.println("running ml script failed!");
            }
            retJson.put("errorMessage",errorMessage);
            retJson.put("state",state);
            retJson.put("result",result);
            return retJson;
        }
    
    如果有来生,一个人去远行,看不同的风景,感受生命的活力。。。
  • 相关阅读:
    wpf 用c#代码给img指定uri
    c 指针作为出参
    wpf获得系统毫秒数
    绑定元素的长宽(Canvas的子类自动伸展)
    PB与COM之关于创建COM,MTS, and COM+组件(1)
    ASA破解密码
    遭遇奸商(显卡篇)
    “启动Word时提示出错,只能用安全模式才能打开”的解决方法
    PowerSocket对象与HostName
    制做集成SATA驱动的XP安装盘
  • 原文地址:https://www.cnblogs.com/Frank99/p/9811244.html
Copyright © 2020-2023  润新知