这几天出于项目的原因研究了一下 java端调用 Python脚本的问题
1. 导入需要依赖的 jar包,(此处使用的 maven)
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.0</version>
</dependency>
2. 创建 Python脚本文件,test.py
#!/usr/bin/python
# -*- coding: UTF-8 -*- // 在需要传递或输出中文字符时,需要设置编码集
def helloEn():
print 'hello world';
def helloCh():
print '你好,世界';
def inparamEn(param):
print param;
def inparamCh(param):
print param;
def resultEn():
return "{'id':298477823792734, 'name':'lilei', 'gender':'lady', 'age':19}";
def resultCh():
return "{'id':298477823792734, 'name':'李雷', 'gender':'男', 'age':19}";
def mthdEn(args):
print args;
return args;
def mthdCh(args):
print args;
return args;
3. 编写测试代码调用 Python脚本
import org.python.core.Py;
import org.python.core.PyFunction;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class JavaInvokPython {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("D:/tmp/test.py");
// 调用英文 helloword/*PyFunction pyFunction = interpreter.get("helloEn", PyFunction.class);
PyObject obj = pyFunction.__call__();
System.out.println(obj);*/
// 调用中文 helloword 需要在脚本上设置 UTF-8编码
/*PyFunction pyFunction = interpreter.get("helloCh", PyFunction.class);
PyObject obj = pyFunction.__call__();
System.out.println(obj);*/
// 调用英文 传参
/*PyFunction pyFunction = interpreter.get("inparamEn", PyFunction.class);
PyObject obj = pyFunction.__call__(new PyString("hello, word"));
System.out.println(obj);*/
// 调用中文 传参 需要在脚本上设置 UTF-8编码
PyFunction pyFunction = interpreter.get("inparamCh", PyFunction.class);
PyObject obj = pyFunction.__call__(Py.newStringUTF8("你好,世界"));
System.out.println(obj);
// 调用英文 返回值
/*PyFunction pyFunction = interpreter.get("resultEn", PyFunction.class);
PyObject obj = pyFunction.__call__();
System.out.println(obj);*/
// 调用中文 返回值
/*PyFunction pyFunction = interpreter.get("resultCh", PyFunction.class);
PyObject obj = pyFunction.__call__();
System.out.println(obj);*/
// 调用英文 参数+返回值
/* PyFunction pyFunction = interpreter.get("mthdEn", PyFunction.class);
PyObject obj = pyFunction.__call__(Py.newStringUTF8("{'id':298477823792734, 'name':'lilei', 'gender':'lady', 'age':19}"));
System.out.println(obj);*/
// 调用英文 参数+返回值
/*PyFunction pyFunction = interpreter.get("mthdCh", PyFunction.class);
PyObject obj = pyFunction.__call__(Py.newStringUTF8("{'id':298477823792734, 'name':'李雷', 'gender':'男', 'age':19}"));
String str = new String(obj.toString().getBytes("ISO-8859-1"), "UTF-8"); // 中文返回值乱码的解决方案: 字符串编码格式的转换
System.out.println(str);*/
4. 总结
(1.) Python默认的编码格式为 ASCII,所以在python脚本中输出中文或向脚本传递中文参数的话会问题,
解决方法:在脚本端设置编码格式为 UTF-8,对中文的参数使用 Py.newStringUTF8封装
(2.) 最后需要注意的是返回值的中文乱码问题,需要对返回的 PyObject对象进行 "UTF-8"转码。
String str = new String(pyObj.toString().getBytes("ISO-8859-1"), "UTF-8");