最近在研究Jython调用python,总结一下可行方案
引入jar包
org.python jython 2.7.2 org.python jython-standalone 2.7.2
注意事项
- 引入第三方库时,会出现找不到情况,通过props.put(“python.home”, pyHome);可以解决,pyHome为引入jython-standalone-2.7.2.jar包的解压路径,用本机python库所在位置是不行的
- 当在python脚本想引入另一个我们自己写的脚本时也会出现找不到的情况,这时我们要通过interpreter.exec(“sys.path.append(”" + 我们自己脚本的位置 + “”)");将我们写的脚本添加进去
- 在脚本中引入的第三方库也要在Java代码中引入一下,例如python写了import sys 那在Java代码中就要写interpreter.exec(“import sys”);
完整代码
整个功能是将jsonStr中温度所对应的值乘以1000再返回,调用了第三方库json,在main.py中调用了我们自己写的test_pyExec.py
Test.java
import org.python.core.Py;
import org.python.core.PyFunction;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
import java.util.Properties;
public class Test {
public static void main(String[] args) {
String pyHome = "C:\Users\18511\.m2\repository\org\python\jython-standalone\2.7.2\jython-standalone-2.7.2";
String pyPath = "src/main/java/main.py";
String jsonStr = "{ "温度": 60, "湿度": 10 }";
String prop = "温度";
String pyScriptPosition = "src/main/java/";
String pyName = "test_pyExec";
Properties props = new Properties();
props.put("python.home", pyHome);
props.put("python.console.encoding", "UTF-8");
props.put("python.security.respectJavaAccessibility", "false");
props.put("python.import.site", "false");
Properties properties = System.getProperties();
PythonInterpreter.initialize(properties, props, new String[0]);
String pyPosition = "sys.path.append("" + pyScriptPosition + "")";
String importPyScript = "from " + pyName + " import main";
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys");
interpreter.exec(pyPosition);
interpreter.exec(importPyScript);
interpreter.execfile(pyPath);
PyFunction execPyScript = interpreter.get("execPyScript", PyFunction.class);
// Py.newStringOrUnicode(jsonStr)解决json串中带有中文问题
PyObject json = execPyScript.__call__(Py.newStringOrUnicode(jsonStr), Py.newStringOrUnicode(prop));
System.out.println(json);
interpreter.cleanup();
interpreter.close();
}
}
main.py
#encoding: utf-8
import sys
import json
from test_pyExec import main
def execPyScript(strJson, prop):
return main( json.loads( json.loads( json.dumps( strJson, ensure_ascii=False ) ) ), prop)
test_pyExec.py
#encoding: utf-8
import json
def main( param, prop ):
param[prop] = param[prop]*1000
return json.dumps(param, ensure_ascii=False)
代码结构
如果有用的话点个赞再走吧



