java集成Jpython解决Caused by: org.python.core.PyException: null问题

java集成Jpython解决Caused by: org.python.core.PyException: null问题

整合Jpython


  org.python
  jython-standalone
  2.7.0

项目中的应用

public static String pyCalculate(String expression) {
		PythonInterpreter interpreter = new PythonInterpreter();
		interpreter.exec("import sys");
		interpreter.exec("result = " + expression);
		Object result = interpreter.get("result");
		return Func.toStr(result);
	}
var latexExpression = ExpressParseUtil.parseLatexExpression(expression);
		latexExpression = ExpressParseUtil.doTranslateExpression(latexExpression).replace("^", "**");
		latexExpression = ExpressParseUtil.insertSpecialCode(latexExpression);
		log.info("转换后的表达式是:{}", latexExpression);
		String result;
		try {
			result = ExpressParseUtil.pyCalculate(latexExpression);
			String[] splits = result.split("\\.");
			if (splits.length > 1) {
				result = splits[0] + "." + splits[1].substring(0, Math.min(splits[1].length(), 4));
			}
		} catch (Exception e) {
			log.error("计算出现错误,计算公式:{},错误原因:{}", latexExpression, e.getMessage());
			return R.fail("计算公式出现异常,请认真比对计算的表达式:" + retExpression + "和传入的参数:" + JSONObject.toJSONString(params));
		}

上述pyCalculate方式在本地使用时没有问题,但是部署到开发环境就会报错

Caused by: org.python.core.PyException: null
at org.python.core.Py.ImportError(Py.java:328)
at org.python.core.Py.importSiteIfSelected(Py.java:1563)
at org.python.util.PythonInterpreter.(PythonInterpreter.java:116)
at org.python.util.PythonInterpreter.(PythonInterpreter.java:94)
at org.python.util.PythonInterpreter.(PythonInterpreter.java:71)
at com.goldnet.greenFinance.utils.ExpressParseUtil.pyCalculate(ExpressParseUtil.java:203)
at com.goldnet.greenFinance.utils.ExpressParseUtil.parseExpression(ExpressParseUtil.java:47)
… 105 common frames omitted

报错原因是没有初始化PythonInterpreter

解决方式,更改pyCalculate方法如下

public static String pyCalculate(String expression) {
		Properties props = new Properties();
		props.put("python.home", "../jython-standalone-2.7.0");
		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]);
		PythonInterpreter interpreter = new PythonInterpreter();
		interpreter.exec("import sys");
		interpreter.exec("result = " + expression);
		Object result = interpreter.get("result");
		return Func.toStr(result);
	}

你可能感兴趣的:(java,服务器,linux)