这篇笔记主要记录了我使用jython的一些问题点:
首先,jython是一个Java写的用来解析python语言的工具,他可以做到运行环境中没有python也可以使用python。
jython采用的方式是优先使用本机的python2,如果没有检测到本机的python2,则会去寻找jython.rar或者本机安装好的jython运行环境。
下面是我写的一些jython的代码:
PySource,因为jython启动之后需要关闭,而且启动一个实例的时间挺长的,所以最好是做成静态类:
package com.shinho.bi.db; import org.python.util.PythonInterpreter; public class PySource { public static PythonInterpreter inter; public static void init(){ inter = new PythonInterpreter(); } }
jython使用方法,里面有入参和出参的传递:
/** * 特殊数据处理方法 * @param key 模板关键字 * @param list 查询出来的结果集 * @throws TemplateException * @throws IOException */ public static String MathMethod(String key, String json){ Cache<String, Object> myCache = EhcacheUtil.cacheManager.getCache("myCache", String.class, Object.class); Map<String, String> tpls = (Map<String, String>)myCache.get("sqls"); String res = ""; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss"); String sqlModel = tpls.get(key); StringWriter out = null; try { PySource.inter.set("ds", json); out = new StringWriter(); PySource.inter.setOut(out); logger.info("begin time:"+sdf.format(new Date())); PySource.inter.exec(sqlModel); //调试的时候取本地代码 //PySource.inter.execfile("/home/wp/Code/SQLModel/python/daily.py"); //调试的时候取本地代码 logger.info("end time:"+sdf.format(new Date())); res = out.toString(); logger.info(res); } catch (Exception e) { e.printStackTrace(); }finally{ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } return res; }
python模板
#coding:utf-8 import sys import json import time import calendar if __name__ == '__main__': model = json.loads(ds) rdc1 = model[0] goal = model[1][0] ly = model[1][1] ny = time.strftime("%Y", time.localtime()) nm = time.strftime("%m", time.localtime()) nd = time.strftime("%d", time.localtime()) nym = time.strftime("%Y%m", time.localtime()) monthRange = calendar.monthrange(int(ny),int(nm))[1] dayNow = int(nd) avg_goal = float(goal['mapList'][0]['value'])/monthRange avg_ly = float(ly['mapList'][0]['value'])/monthRange rdcList = [] goalList = [] lyList = [] vsGoal = [] vsLy = [] vsGoalLv = [] vsLyLv = [] i = 1 nowBgt = 0 nowLy = 0 while (i <= monthRange): dd = str(i) if i < 10: dd = '0'+str(i) nowBgt = nowBgt + avg_goal nowLy = nowLy + avg_ly goalMap = {'key': nym + dd, 'value': nowBgt} lyMap = {'key': nym + dd, 'value': nowLy} goalList.append(goalMap) lyList.append(lyMap) i = i+1 goalCard = {'index': 'MRL2', 'mapList': goalList} lyCard = {'index': 'MRL3', 'mapList': lyList} nowVal = 0 i = 1 while (i <= dayNow): dd = str(i) if i < 10: dd = '0'+str(i) if i-1 < len(rdc1[0]["mapList"]): key = rdc1[0]["mapList"][i-1]["key"] value = 0 if key == nym + dd: value = float(rdc1[0]["mapList"][i-1]["value"]) else: value = 0 else: value = 0 nowVal = nowVal + value rdcMap = {'key': nym + dd, 'value': nowVal} rdcList.append(rdcMap) dayGoal = 0 dayLy = 0 for gMap in goalList: if gMap["key"] == (nym + dd) : dayGoal = float(gMap["value"]) break for lMap in lyList: if lMap["key"] == (nym + dd): dayLy = float(lMap["value"]) break # 计算vs vsGoalMap = {'key': nym + dd, 'value': (nowVal-dayGoal)} vsLyMap = {'key': nym + dd, 'value': (nowVal-dayLy)} vsGoal.append(vsGoalMap) vsLy.append(vsLyMap) vsGoalLvMap = {'key': nym + dd, 'value': (nowVal/dayGoal)-1} vsLyLvMap = {'key': nym + dd, 'value': (nowVal/dayLy)-1} vsGoalLv.append(vsGoalLvMap) vsLyLv.append(vsLyLvMap) i = i+1; rdcCard = {'index': 'MRL1', 'mapList': rdcList} vsGoalCard = {'index': 'MRL4', 'mapList': vsGoal} vsLyCard = {'index': 'MRL5', 'mapList': vsLy} vsGoalLvCard = {'index': 'MRL6', 'mapList': vsGoalLv} vsLyLvCard = {'index': 'MRL7', 'mapList': vsLyLv} resList = [rdcCard, goalCard, lyCard, vsGoalCard, vsLyCard, vsGoalLvCard, vsLyLvCard] print resList
最后,是如何控制jython使用本机python的,指定python路径:
其中只有第一个put有用哦
Properties props = new Properties(); props.put("python.path", "/usr/bin/python"); props.put("python.console.encoding", "UTF-8"); props.put("python.security.respectJavaAccessibility", "false"); props.put("python.import.site", "false"); Properties preprops = System.getProperties(); PythonInterpreter.initialize(preprops, props, new String[0]);