私信  •  关注

Shan Chathusanda Jayathilaka

Shan Chathusanda Jayathilaka 最近回复了
6 年前
回复了 Shan Chathusanda Jayathilaka 创建的主题 » 使用Jython从Java中使用Python函数运行Python函数

根据这个问题的上述评论部分的建议,我已经制定了我的问题的解决方案。下面的代码段将演示这一点。在这个解决方案中,我设置了 Python路径 作为模块文件的目录路径。

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路径 作为 所有模块的父目录路径 以便检测所有模块。