java 如何调用python代码?

Jython: Python for the Java Platform - Home | Jython

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

参考连接:

Calling Python in Java? - Stack Overflowjava 如何调用python代码?https://*.com/questions/8898765/calling-python-in-java

上一篇:libass简明教程


下一篇:QQ音乐的动效歌词是如何实践的?