【问题标题】:How to provide python package path in Jython/Java code?如何在 Jython/Java 代码中提供 python 包路径?
【发布时间】:2017-10-27 00:38:52
【问题描述】:

我从这个链接中获取了一个书面样本来编写我的 Python + Java 集成代码。

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

代码如下所示。

package org.jython.book.interfaces;

import org.jython.book.interfaces.JythonObjectFactory;
import org.python.core.Py;
import org.python.core.PyString;
import org.python.core.PySystemState;

public class Main {

    public static void main(String args[]) {

        String projDir = System.getProperty("user.dir");
        String rootPath = projDir + "/src/org/jython/book/interfaces/";
        String modulesDir = projDir + "/src/org/jython/book/interfaces/";

        System.out.println("Project dir: " + projDir);

        PySystemState sysSt = Py.getSystemState();
        JythonObjectFactory factory = new JythonObjectFactory(sysSt, BuildingType.class, "Building", "Building");

        BuildingType building = (BuildingType) factory.createObject();

        building.setBuildingName("BUIDING-A");
        building.setBuildingAddress("100 MAIN ST.");
        building.setBuildingId(1);

        System.out.println(building.getBuildingId() + " " +
            building.getBuildingName() + " " +
            building.getBuildingAddress());
    }

}

当我运行这段代码时,它会抛出一个错误,它没有找到 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

【问题讨论】:

    标签: java python jython


    【解决方案1】:

    您好,找到了这个问题的答案!

    添加了 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 );
    

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

    module=<module 'Building' from '/Users/eclipsews/PythonJava/src/org/jython/book/interfaces/Building$py.class'>,class=<class 'Building.Buildin
    g'>
    1 BUIDING-A 100 MAIN ST.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-06
      • 2012-04-23
      相关资源
      最近更新 更多