为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕尼黑5688855 2022-06-15 09:24:59
我想使用 jython 执行一个 Python 函数,该函数位于我的一个来自 java 的 python 项目中。https://smartbear.com/blog/test-and-monitor/embedding-jython-in-java-applications/正在为此目的提供示例代码。但在我的场景中,我遇到了以下异常。线程“main” Traceback 中的异常(最近一次调用最后一次):文件“”,第 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 程序会生成上述异常。我想知道这个提到的代码段有什么问题。
查看完整描述

1 回答

?
繁华开满天机

TA贡献1816条经验 获得超4个赞

根据该问题上述评论部分的建议,我已经为我的问题制定了解决方案。以下代码段将证明这一点。在这个解决方案中,我将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添加为所有模块的父目录路径,以便检测所有模块。


查看完整回答
反对 回复 2022-06-15
  • 1 回答
  • 0 关注
  • 129 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号