public class CallPython {
/**
*
* 直接调用python执行语句<br>
* @param cmd
* @author:任聪
* @date:last updated time 2016年10月8日
*/
public static void invoke(String[] commands){
PythonInterpreter interpreter = new PythonInterpreter();
for(String command : commands)
interpreter.exec(command);
}
/**
*
* 调用python py文件<br>
* @param is
* @author:任聪
* @date:last updated time 2016年10月8日
*/
public static void invoke(InputStream is){
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile(is);
}
/**
*
* 调用python py文件下的方法<br>
* @param is : 文件输入流
* @param method :方法名称
* @param args :参数列表
* @return
* @author:任聪
* @date:last updated time 2016年10月8日
*/
public static PyObject invoke(InputStream is,String method,PyObject... args ){
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile(is);
PyFunction func = (PyFunction)interpreter.get(method,PyFunction.class);
PyObject pyobj = func.__call__(args);
return pyobj;
}
public void command(){
String commands[] = new String[]{
"# -*- coding: utf-8 -*- ",
"hobby_arr = ('play','sing','dance'); ",
"print (hobby_arr[0]);" };
CallPython.invoke(commands);
}
}
<dependency>
<groupId>org.python</groupId>
<artifactId>jython</artifactId>
<version>2.5.3</version>
</dependency>