Java中调用Python代码片段

Python代码:D: \\ test.py

 

def test(a, b):
    return a + b
print "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 python
a+b = 2018

 

 

 

 

 

你可能感兴趣的:(Java)