1.下载jpython.jar的链接:http://download.csdn.net/detail/haleyliu123/9862861
2.在Java类中直接执行Python语句
package com.lrq.test; import java.io.UnsupportedEncodingException; import java.util.Properties; import org.python.util.PythonInterpreter; public class FristPython { public static void main(String args[]) throws UnsupportedEncodingException { Properties props = new Properties(); props.put("python.console.encoding", "UTF-8"); Properties preprops = System.getProperties(); PythonInterpreter.initialize(preprops, props, new String[0]); PythonInterpreter interpreter = new PythonInterpreter(); String swords=new String("swords=('tianWen','渊虹','太阿','干将','莫邪','雪霁','水寒'); ".getBytes("ISO-8859-1"),"UTF-8"); interpreter.exec(swords); interpreter.exec("print swords[0].encode('utf-8');"); } }
结果:
3. 在java中调用python脚本中的函数
#!/user/bin/python def plusFunc(a, b): return a + b package com.lrq.test; import java.io.UnsupportedEncodingException; import org.python.core.PyFunction; import org.python.core.PyInteger; import org.python.core.PyObject; import org.python.util.PythonInterpreter; public class UsePythonFunction { public static void main(String args[]) throws UnsupportedEncodingException { PythonInterpreter interpreter = new PythonInterpreter(); interpreter.execfile("test.py"); PyFunction func = (PyFunction) interpreter.get("plusFunc",PyFunction.class); int a =12, b = 2; PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b)); //转码 String newStr = new String(pyobj.toString().getBytes("iso8859-1"), "utf-8"); System.out.println("anwser = " + newStr); } }
结果:
4. 使用java直接执行python脚本
#open files print 'hello' number=[3,5,2,0,6] print number number.sort() print number number.append(0) print number print number.count(0) print number.index(5) package com.lrq.test; import org.python.util.PythonInterpreter; public class ExcutePythonFile{ public static void main(String args[]){ PythonInterpreter interpreter = new PythonInterpreter(); interpreter.execfile("input.py"); } } 结果: