Calling Python in Java?

前端 未结 11 1374
北荒
北荒 2020-11-22 13:04

I am wondering if it is possible to call python functions from java code using jython, or is it only for calling java code from python?

11条回答
  •  不要未来只要你来
    2020-11-22 13:18

    Jython: Python for the Java Platform - http://www.jython.org/index.html

    You can easily call python functions from Java code with Jython. That is as long as your python code itself runs under jython, i.e. doesn't use some c-extensions that aren't supported.

    If that works for you, it's certainly the simplest solution you can get. Otherwise you can use org.python.util.PythonInterpreter from the new Java6 interpreter support.

    A simple example from the top of my head - but should work I hope: (no error checking done for brevity)

    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.exec("import sys\nsys.path.append('pathToModules if they are not there by default')\nimport yourModule");
    // execute a function that takes a string and returns a string
    PyObject someFunc = interpreter.get("funcName");
    PyObject result = someFunc.__call__(new PyString("Test!"));
    String realResult = (String) result.__tojava__(String.class);
    

提交回复
热议问题