python代码如下
#coding:utf-8
def keywordsRouter(keywords):
str = keywords+"这里是中文";
print("py=="+str);
return str;
java代码如下
Properties props = new Properties();
// props.put("python.home","path to the Lib folder");
props.put("python.console.encoding", "UTF-8"); // Used to prevent: console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.
props.put("python.security.respectJavaAccessibility", "false"); //don't respect java accessibility, so that we can access protected members on subclasses
props.put("python.import.site","false");
Properties preprops = System.getProperties();
PythonInterpreter.initialize(preprops, props, new String[0]);
PythonInterpreter interp = new PythonInterpreter();
String ret = "";
String pyfilePath = ".py文件的路径";
interp.execfile(pyfilePath);
PyFunction func = (PyFunction)interp.get("keywordsRouter",PyFunction.class);
PyObject pyobj = func.__call__(new PyString("传给keywordsRouter方法的参数"));
ret = pyobj.toString();//这里ret可能会乱码
String newStr = new String(ret.getBytes("iso8859-1"), "utf-8"); //通过new String(ret.getBytes("iso8859-1"), "utf-8")转一下就好了
System.out.println("anwser= " +newStr); //newStr就不会乱码了
return newStr;