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

问题描述 投票:1回答:1

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

线程“main”Traceback中的异常(最近一次调用last):ImportError中的文件“”,第1行:没有名为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程序将生成上述异常。我想知道这个被管理的代码段有什么问题。
java python jython jython-2.7
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添加为所有模块的父目录路径,以便检测所有模块。

© www.soinside.com 2019 - 2024. All rights reserved.