使用Java

时间:2019-04-03 07:32:25

标签: java python jython

我需要使用java获取python方法的结果。我使用Jython调用我在python中编写的用于打印“ Hello World”的方法。

这是python代码,

class Hello:

    def run(self):
        print('Hello world!')

这是我为调用此方法而编写的Java代码。

public static void main(String[] args) {
        Properties props = new Properties();
        props.setProperty("python.path", "D:\\Github Repositories\\OntoVec\\");
        PythonInterpreter.initialize(System.getProperties(), props, new String[]{""});
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("from NewModule.TestJython import TestJython");
        PyInstance instance = (PyInstance) interpreter.eval("TestJython()");
        PyMethod method = (PyMethod) instance.__getattr__("run");
        PyObject object = method.__call__();
}

执行此代码时,出现以下错误。我将其实现为将Jython 2.7.0依赖项导入pom.xml的Maven项目。我在Windows环境中执行此操作,“ D:\ Github存储库\ OntoVec \”是python项目的路径。 “ TestJython”是python文件的名称,“ run”是python方法的名称。

Exception in thread "main" ImportError: Cannot import site module and its dependencies: No module named site
Determine if the following attributes are correct:
  * sys.path: ['D:\\Github Repositories\\OntoVec\\', 'C:\\Users\\Akila Amarasinghe\\.m2\\repository\\org\\python\\jython\\2.7.0\\Lib', '__classpath__', '__pyclasspath__/']
    This attribute might be including the wrong directories, such as from CPython
  * sys.prefix: C:\Users\Akila Amarasinghe\.m2\repository\org\python\jython\2.7.0
    This attribute is set by the system property python.home, although it can
    be often automatically determined by the location of the Jython jar file

You can use the -S option or python.import.site=false to not import the site module

有人可以显示如何调用python方法吗?请指出我是否做错了。感谢帮助。

0 个答案:

没有答案