java调用python计算

1、首先你的java服务环境部署,安装python

2、pythonPath为你python的安装路径

       windows:python

       linux:/data/anaconda/bin/python3.7

     pyPath:调用python文件地址,可以直接放在java项目路径中,也可以放在本地文件夹

    后面参数为调用python传递的参数

	/**
	 * call python script 
	 * @param paramsList --all need parameters to execute script
	 * @throws JSONException 
	 */
	public static JSONObject runPyScriptByParams(String pyPath,String sourceShpPath,String depVar,String variables,String outputFile,String calculaterTypes) throws JSONException {
		
		//log.info("excute runPyScriptByParams method ....");
		System.out.println("excute runPyScriptByParams method ....");
		JSONObject response = new JSONObject();
		String[] parametersArr = new String[] {ToolsResource.pythonPath,pyPath,sourceShpPath,depVar,variables,outputFile,calculaterTypes};
		log.info(Arrays.toString(parametersArr));
		try {
			Process pr = Runtime.getRuntime().exec(parametersArr);
			BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
			
            String line;
            while ((line = in.readLine()) != null) {// must have this, or the python script not execute  
            	log.info("line == "+ line);//print python script execute info 
                if(line.toLowerCase().contains("error")) {
                	log.info("error == "+ line);
                	response.put("error",line);
                }
            }
            
            in.close();
            pr.waitFor();
            response.put("success", "running sucess!");
		} catch (Exception e) {
			e.printStackTrace();
			response.put("error", e.toString());
			System.out.println(e);
		}
		return response;
	}

3、python文件:main方法中获取传递过来的参数,调用方法执行

if __name__ == '__main__':

    #LOG_FORMAT = "%(asctime)s  - %(name)s - %(levelname)s - %(message)s"
    #logging.basicConfig(filename='wayhe_gwr.log', level=logging.DEBUG, format=LOG_FORMAT)
    #logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=LOG_FORMAT)
    #logging.FileHandler('gwrPython.log')
    
    print("execute script main method ")
    print(sys.getdefaultencoding())
    for i in range(1, len(sys.argv)):
        #print("get parameters == %s" % sys.argv[i])
        if i == 1:
             if '>>>>' in sys.argv[i]:
                shpPath = sys.argv[i].replace('>>>>', ':')  # windows path
             else:
                shpPath = sys.argv[i]
        if i == 2:
            depVarName = sys.argv[i]
        if i == 3:
            varilables = sys.argv[i]
        if i == 4:
             if '>>>>' in sys.argv[i]:
                outputFile = sys.argv[i].replace('>>>>', ':')  # windows path
             else:
                outputFile = sys.argv[i]
        if i == 5:
            calculaterTypes = sys.argv[i]
        # {a:12456,b:jjshh,c:jhaoe,d:58dhah>88sdd}
        # parase all parameter from java
        
    print('shpPath===%s' % shpPath)
    print('depVarName===%s' % depVarName)
    print('varilables===%s' % varilables)
    print('outputFile===%s' % outputFile)
    print('calculaterTypes===%s' % calculaterTypes)
    
    run = MyGWR()
    try:
        if calculaterTypes == "gwrRegress":
            run.getGWR(shpPath, depVarName, varilables, outputFile)
        else:
            run.getOLS(shpPath, depVarName, varilables, outputFile)
    except:
        #print(sys.exc_info())
        logging.info(sys.exc_info())

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值