我想通过使用jython来执行一个Python函数,它位于我的一个python项目中。 https://smartbear.com/blog/test-and-monitor/embedding-jython-in-java-applications/正在为此目的提供示例代码。但在我的场景中,我得到以下异常。
线程“main”Traceback中的异常(最近一次调用last):ImportError中的文件“”,第1行:没有名为JythonTestModule的模块
我的方案如下。
public static void main(String[] args) throws PyException{
PythonInterpreter pi = new PythonInterpreter();
pi.exec("from JythonTestModule import square");
pi.set("integer", new PyInteger(42));
pi.exec("result = square(integer)");
pi.exec("print(result)");
PyInteger result = (PyInteger)pi.get("result");
System.out.println("result: "+ result.asInt());
PyFunction pf = (PyFunction)pi.get("square");
System.out.println(pf.__call__(new PyInteger(5)));
}
运行此java方法后,java程序将生成上述异常。我想知道这个被管理的代码段有什么问题。从这个问题的上述评论部分的建议,我已经开发了我的问题的解决方案。以下代码段将证明这一点。在这个解决方案中,我将python.path设置为模块文件的目录路径。
public static void main(String[] args) throws PyException{
Properties properties = new Properties();
properties.setProperty("python.path", "/path/to/the/module/directory");
PythonInterpreter.initialize(System.getProperties(), properties, new String[]{""});
PythonInterpreter pi = new PythonInterpreter();
pi.exec("from JythonTestModule import square");
pi.set("integer", new PyInteger(42));
pi.exec("result = square(integer)");
pi.exec("print(result)");
PyInteger result = (PyInteger)pi.get("result");
System.out.println("result: "+ result.asInt());
PyFunction pf = (PyFunction)pi.get("square");
System.out.println(pf.__call__(new PyInteger(5)));
}
如果要使用Jython中的多个模块,请将python.path添加为所有模块的父目录路径,以便检测所有模块。