簡體   English   中英

如何在Jython / Java代碼中提供python包路徑?

[英]How to provide python package path in Jython/Java code?

我從此鏈接中獲取了一個書面示例,以編寫我的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

您好找到了這個問題的答案!

添加了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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM