Python高阶API开发方法
1.使用方法
1.1.虚拟环境配置
通过server_conf.xml中的webRoot参数进行配置虚拟环境路径,程序将自动创建虚拟空间,在该目录下生成.python_embed_venv文件夹,python环境及第三方依赖存储在该文件夹下。
1.2.实例化
实例化PythonEmbedCaller类,参数为:python文件地址/python代码段、python版本(python或python3,传空则默认使用python);
例:PythonEmbedCaller pythonEmbedCaller = new PythonEmbedCaller("/wwwdata/product/udso/dynamic/my_func.py", "python");
1.3.调用
1.3.1.方式1:无参函数 + 手动指定依赖
// 调用无参方法。参数:python方法名、依赖集合
JsonNode result1 = pythonEmbedCaller.callPythonFunctionNoArgs("get_version", Collections.emptyList());
System.out.println(result1.toPrettyString());
1.3.2.方式2:有参函数 + 手动指定依赖
// 设置参数
Map input = new HashMap<>();
input.put("values", Arrays.asList(10.0, 20.0, 30.0));
// 显式声明依赖:numpy 和 pandas
List deps = Arrays.asList("numpy", "pandas");
// 调用有参方法。参数:python方法名、参数、依赖集合
JsonNode result2 = pythonEmbedCaller.callPythonFunctionWithArg("process", input, deps);
System.out.println(result2.toPrettyString());
1.3.3.方式3:自动探测并安装缺失依赖
// 设置参数
Map input = new HashMap<>();
input.put("values", Arrays.asList(1.5, 2.5, 3.5));
// 不传任何依赖列表!系统自动处理。参数:python方法名、参数
JsonNode result3 = pythonEmbedCaller.callPythonFunctionAutoDep("process", input);
System.out.println(result3.toPrettyString());
1.3.4.方式4:执行code而非文件并自动探测依赖
// 定义code
String code =
"def compute(data):n" +
" import mathn" +
" return {'sqrt': math.sqrt(data['x'])}n";
// 设置参数
Map input = new HashMap<>();
input.put("x", 16.0);
// 调用。参数:python代码段、python方法名、参数
JsonNode result4 = pythonEmbedCaller.callPythonCode(code, "compute", input);
System.out.println(result4.toPrettyString());
2.python代码文件:my_func.py示例
注:.py文件需增加# -*- coding: utf-8 -*-指定utf-8
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd # 故意加一个可能未安装的包
import sysdef get_version():
return {"version": "2.0"}def process(data):
arr = np.array(data["values"])
df = pd.DataFrame({"x": arr})
return {
"sum": float(arr.sum()),
"mean": float(arr.mean()),
"rows": len(df)
}def hello_with_progress(n):
# 兼容 Python 2 和 Python 3
if sys.version_info[0] < 3:
print ">>> Python executable:", sys.executable
print ">>> sys.prefix:", sys.prefix
else:
print(">>> Python executable:", sys.executable)
print(">>> sys.prefix:", sys.prefix)
import tqdm
for i in tqdm.tqdm(range(n)):
pass
return {"status": "completed", "count": n}
扫一扫