使用j调用python方法

2024-10-02 00:21:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要使用java获得python方法的结果。我使用Jython调用我用python编写的方法来打印“helloworld”。你知道吗

这是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__();
}

当执行这个代码时,我得到以下错误。我将其实现为一个maven项目,将Jython2.7.0依赖项导入到pom.xml文件. 我在windows环境下执行此操作,“D:\Github Repositories\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方法吗?如果我做错了,请指出。谢谢你的帮助。你知道吗


Tags: the方法run代码importgithubnewsite

热门问题