如何在Jython/Java代码中提供python包路径?

2024-06-29 01:03:58 发布

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

我从这个链接中获取了一个编写Python+Java集成代码的示例。在

http://www.jython.org/jythonbook/en/1.0/JythonAndJavaIntegration.html

代码如下所示。在

^{pr2}$

当我运行这段代码时,它会抛出一个错误:它没有找到python模块。我将.py和.pyc文件保存在提供的“modulesDir”路径下。在

文献中说"the requested module must be contained somewhere on the sys.path";但是,我不知道如何从这个Java程序设置它。有人能帮忙吗?在

Project dir: /Users/eclipsews/PythonJava
Exception in thread "main" ImportError: No module named Building

Tags: the代码orghttp示例链接htmlwww
1条回答
网友
1楼 · 发布于 2024-06-29 01:03:58

嗨找到了这个问题的答案!在

添加了PySystemState.initialize方法,其中我显式提供python.path属性,它初始化为我的项目路径,其中python模块可用。在

private static Properties setDefaultPythonPath(Properties props) {

    String pythonPathProp = props.getProperty("python.path");
    String new_value;

    if (pythonPathProp == null) {
        new_value  = System.getProperty("user.dir") + "/src/org/jython/book/interfaces/";       
    }

    props.setProperty("python.path", new_value);
    return props;
}

Properties props = setDefaultPythonPath(System.getProperties());
PySystemState.initialize( System.getProperties(), props, null );

这将产生如下正确的输出:

^{pr2}$

相关问题 更多 >