Java调用Python

来源:互联网 发布:美国特效软件 编辑:程序博客网 时间:2024/05/20 08:27

Python代码:D: \\ test.py

def test(a, b):    return a + bprint "Java To python";

Java代码:


import java.util.Properties;import org.python.core.PyFunction;import org.python.core.PyInteger;import org.python.core.PyObject;import org.python.util.PythonInterpreter;/** * Java调用Python代码 */public class JavaConPython{    public static void main(String[] args) {                //Java运行Python文件        Properties props = new Properties();        props.put("python.console.encoding", "UTF-8");        props.put("python.security.respectJavaAccessibility", "false");        props.put("python.import.site", "false");        Properties preprops = System.getProperties();                PythonInterpreter.initialize(preprops, props, new String[0]);                PythonInterpreter interpreter = new PythonInterpreter();          interpreter.execfile("D:\\test.py");                        //Java调用Python方法        PyFunction func = (PyFunction) interpreter.get("test", PyFunction.class);        int a = 2016, b = 2;        PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));        String ret = "a+b = " + pyobj.toString();        System.out.println(ret);        interpreter.close();    }}

运行结果:

Java To pythona+b = 2018



0 0