使用 jython 运行带有来自 java 的参数的 python 函数

我想使用 jython 执行一个 Python 函数,该函数位于我的一个来自 java 的 python 项目中。https://smartbear.com/blog/test-and-monitor/embedding-jython-in-java-applications/正在为此目的提供示例代码。但在我的场景中,我遇到了以下异常。

线程“main” Traceback 中的异常(最近一次调用最后一次):文件“”,第 1 行,在 ImportError 中:没有名为 JythonTestModule 的模块

我的情况如下。

  1. 我使用包含以下函数的 PyCharm(JythonTestModule.py) 在我的 python 项目(pythonDev) 中创建了一个 python 模块。

    def square(value): 返回值*值

  2. 然后我在我的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 程序会生成上述异常。我想知道这个提到的代码段有什么问题。


慕尼黑5688855
浏览 130回答 1
1回答

繁华开满天机

根据该问题上述评论部分的建议,我已经为我的问题制定了解决方案。以下代码段将证明这一点。在这个解决方案中,我将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添加为所有模块的父目录路径,以便检测所有模块。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java