使用jython运行带有java参数的python函数
我想使用jython执行一个Python函数,该函数位于我的一个java Python项目中。正在为此目的提供示例代码。但在我的场景中,我得到了以下例外 线程“main”回溯中出现异常(最近一次调用last):文件 “”中的第1行:没有名为“”的模块 JythonTestModule 我的设想如下使用jython运行带有java参数的python函数,java,python,jython,jython-2.7,Java,Python,Jython,Jython 2.7,我想使用jython执行一个Python函数,该函数位于我的一个java Python项目中。正在为此目的提供示例代码。但在我的场景中,我得到了以下例外 线程“main”回溯中出现异常(最近一次调用last):文件 “”中的第1行:没有名为“”的模块 JythonTestModule 我的设想如下 我使用PyCharm(JythonTestModule.py)在python项目(pythonDev)中创建了一个python模块,该模块包含以下函数 def平方(值): 返回值*值 然后,我在jav
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添加为所有模块的父目录路径,以检测所有模块。找不到JythonTestModule。JythonTestModule.py是否与Java项目位于同一目录中?它很可能在错误的目录中查找模块(我不知道答案,但是)。既然
JythonTestModule
是您的模块,您如何确保解释器知道它?除了系统模块之外,它在哪里寻找其他模块?@M.Goodman,我认为他只需要将解释器的python.path
属性设置为他的基目录。@ShanChathusandaJayathilaka,可能会有帮助吗?我想是的。我不确定。