[英]Run a python function with arguments from java using jython
我想使用 jython 执行一个 Python 函数,该函数位于我的一个 Python 项目中。 https://smartbear.com/blog/test-and-monitor/embedding-jython-in-java-applications/为此目的提供了示例代码。 但在我的场景中,我得到了以下异常。
线程“main”回溯中的异常(最近一次调用最后一次):文件“”,第 1 行,在 ImportError 中:没有名为 JythonTestModule 的模块
我的情况如下。
我使用包含以下函数的 PyCharm(JythonTestModule.py) 在我的 python 项目(pythonDev)中创建了一个 python 模块。
def square(value): 返回值*值
然后我在我的 java 项目(javaDev)中创建了一个示例 java 类并调用了 python 模块。
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添加为所有模块的父目录路径,以便检测所有模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.