javapythonjython

Calling Python in Java?


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?


Solution

  • 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);
    

    As of 2021, Jython does not support Python 3.x