我想知道是否可以使用 Jython 从 Java 代码调用 Python 函数,还是只能从 Python 调用 Java 代码?
最佳答案
Jython:用于 Java 平台的 Python - http://www.jython.org/index.html
您可以使用 Jython 从 Java 代码轻松调用 python 函数。只要你的 python 代码本身在 jython 下运行,即不使用一些不受支持的 c 扩展。
如果这对您有用,那么它肯定是您可以获得的最简单的解决方案。否则,您可以使用新的 Java6 解释器支持中的 org.python.util.PythonInterpreter
。
我脑海中的一个简单示例 - 但我希望应该可以工作:(为简洁起见,没有进行错误检查)
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);
截至 2021 年,Jython 不支持 Python 3.x
关于java - 在 Java 中调用 Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8898765/