jep使用
jep使用JNI和CPython API来启动JVM中的Python解释器。当你在Java中创建一个Interpreter实例时,将为该Java Interpreter实例创建一个Python解释器,并保留在内存中,直到用Interpreter.close()关闭该Interpreter实例。由于需要管理一致的Python线程状态,创建Interpreter实例的线程必须在对该Interpreter实例的所有方法调用中重复使用。Jep应该与任何纯Python模块一起工作。它可以与各种CPython扩展一起工作。开发人员报告说,Jep可以与NumPy、Scipy、Pandas、TensorFlow、Matplotlib、cvxpy等一起工作。
使用方式如下:
首先我们需要python运行环境,jep能很好的支持python2.0以及3.0,这里我们以3.8为例(jep目前最高支持python3.8,框架还在持续更新中)。
安装好python运行环境后我们安装jep
pip3 install jep
配置jep的库名路径export LD_LIBRARY_PATH=“<your_user_path>/myenv/lib/python3.8/site-packages/jep”$LD_LIBRARY_PATH(如果不生效,则在java程序运行时指定库地址-Djava.library.path=/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/jep/)
java程序引入jep的jar包
<dependency>
<groupId>black.ninia</groupId>
<artifactId>jep</artifactId>
<version>4.0.3</version>
</dependency
/**
* 从python中拿到变量值
* @param scriptContent
*/
public void runScriptWithReturn() {
try (SharedInterpreter interpreter = new SharedInterpreter()) {
interpreter.exec("import sys");
Object value = interpreter.getValue("sys.path");
System.out.println(value);
}
}
/**
* 调用python文件中的方法
*/
public void runScriptWithFileMethod() {
JepConfig jepConfig = new JepConfig().addIncludePaths("/Users/rayduan/PycharmProjects/pythonProject");
SharedInterpreter.setConfig(jepConfig);
try (Interpreter interpreter = new SharedInterpreter()) {
interpreter.exec("from demo import *");
Object result = interpreter.invoke("func", 1, 2);
System.out.println(result);
}
}
/**
* 通过python脚本修改变量中的值
*/
public void runScriptWithChangeParam() {
try (Interpreter interpreter = new SharedInterpreter()) {
Map<String, Object> binding = new HashMap<>();
binding.put("name", "zhangshan");
binding.put("age", "18");
interpreter.set("vars", binding);
interpreter.exec("vars['name'] = 'ls'");
Map vars = interpreter.getValue("vars", Map.class);
System.out.println(vars);
}
}
根据我们需求,jep能完全覆盖我们的使用场景,下面我们说下jep的优缺点。
优点:
无需将脚本生成文件管理,直接执行脚本字符串即可
可以支持各种版本的python
支持各种形式的第三方包
使用方便,能和java程序进行很好的交互
缺点:
搭建环境较为复杂

浙公网安备 33010602011771号