[英]Jython: Can not import python function in Java
我正在尝试开发一个简单的 Java 应用程序,我希望它使用 Jython 使用一些 Python 代码。 我正在尝试从文件中运行 python 方法并收到此错误:
ImportError: cannot import name testFunction
只是尝试一个简单的例子,所以我可以看到问题出在哪里。 我的 python 文件test.py
是这样的:
def testFunction():
print("testing")
还有我的 Java class:
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("path_to_file\\test.py");
interpreter.exec("from test import testFunction");
因此它可以正确找到该模块,但其行为就像内部没有名为testFunction
的 function 一样。
执行脚本文件如下。
interpreter.execfile("path/to/file/test.py");
如果您在脚本文件中声明了函数,那么在执行上述语句后,您将可以从程序中执行这些函数,如下所示。
interpreter.exec("testFunction()");
因此,您不需要任何导入语句。
完整的示例代码:
package jython_tests;
import org.python.util.PythonInterpreter;
public class RunJythonScript2 {
public static void main(String[] args) {
try (PythonInterpreter pyInterp = new PythonInterpreter()) {
pyInterp.execfile("scripts/test.py");
pyInterp.exec("testFunction()");
}
}
}
脚本:
def testFunction():
print "testing"
Output:
testing
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.