Home >Java >javaTutorial >How Can I Run Python Code Within a Java Application?
Can I Execute Python Code from Java?
Jython enables the seamless integration of Python and Java. While typically known for its support in calling Java code from Python, Jython offers reciprocal capabilities. You can indeed invoke Python functions directly from Java code.
To utilize this feature, simply follow these steps:
Here's a concise example:
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);
Please note that as of 2021, Jython does not fully support Python 3.x. Therefore, ensure your Python code adheres to Python 2.x syntax and libraries for compatibility.
The above is the detailed content of How Can I Run Python Code Within a Java Application?. For more information, please follow other related articles on the PHP Chinese website!