java中调用python程序
费了一天的时间,想用Jpython生成的jar文件在java中调用,没有行能,既然行不通,那就反过来吧,在java中直接调用python程序,呵呵,成功了,现在拿出来与大家分享
Jpython jython2.2.1
JDK 1.5
以下是程序代码
python.java
import java.util.List;
import org.python.core.PyException;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class python {
public static void main(String []args)throws PyException
{
PythonInterpreter interp =new PythonInterpreter();
System.out.println("Hello, brave new world";
interp.exec("import sys";
interp.exec("print sys";
interp.set("a", new PyInteger(42));
interp.exec("print 'test='+str(a)";
interp.exec("x = 2+2";
PyObject x = interp.get("x";
System.out.println("x: "+x);
System.out.println("Goodbye, cruel world";
interp.exec("import re";
interp.exec("t =re.compile('^(0{2})IFCSUM)MANIFEST):')";
interp.exec(" a = t.search('00:IFCSUM:MANIFEST:').groups()";
PyObject k = interp.get("a");
List list = ((List)k.__tojava__(List.class));
//System.out.println(k);
System.out.println(list);
}
}