运行 一个 python 函数,参数来自 java 使用 jython

Run a python function with arguments from java using jython

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

Exception in thread "main" Traceback (most recent call last): File "", line 1, in ImportError: No module named JythonTestModule

我的场景如下

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

    def 平方(值): return价值*价值

  2. 然后我在我的 java 项目(javaDev)中创建了一个示例 java class 并调用了 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 作为 所有模块的父目录路径,以便检测所有模块。