Home  >  Article  >  Backend Development  >  How can I call Python functions from Java using Jython?

How can I call Python functions from Java using Jython?

Barbara Streisand
Barbara StreisandOriginal
2024-11-08 04:05:02293browse

How can I call Python functions from Java using Jython?

Invoking Python from Java: Jython's Role

While Jython bridges the Python-Java divide by facilitating the execution of Python code in Java environments, it is crucial to note its primary functionality: enabling the invocation of Java code from Python.

Calling Python Functions from Java with Jython

If your Python code is compatible with Jython (i.e., free from unsupported C extensions), you can seamlessly call Python functions from Java. This approach offers the most straightforward solution for this task.

An Illustrative Example

The following Java code snippet demonstrates how to invoke a Python function that operates on a string and returns a string:

<code class="java">PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('pathToModules if they are not there by default')\nimport yourModule");
PyObject someFunc = interpreter.get("funcName");
PyObject result = someFunc.__call__(new PyString("Test!"));
String realResult = (String) result.__tojava__(String.class);</code>

Alternative Approach for More Complex Scenarios

In cases where Jython is not an appropriate solution, Java 6 introduces the org.python.util.PythonInterpreter. This API provides an alternative for executing Python code from Java.

Note: Jython currently does not support Python 3.x as of 2021.

The above is the detailed content of How can I call Python functions from Java using Jython?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn