[英]How to provide python package path in Jython/Java code?
I have taken a written sample from this link to write my Python + Java integration code. 我从此链接中获取了一个书面示例,以编写我的Python + Java集成代码。
http://www.jython.org/jythonbook/en/1.0/JythonAndJavaIntegration.html
The code looks like below. 代码如下所示。
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());
}
}
When I run this code, it throws an error that it did not find the python module. 当我运行这段代码时,它抛出一个错误,即找不到python模块。 I have kept the .py and .pyc files under the path provided as 'modulesDir'. 我将.py和.pyc文件保留在“ modulesDir”提供的路径下。
The literature says that "the requested module must be contained somewhere on the sys.path"
; 文献说: "the requested module must be contained somewhere on the sys.path"
; however, I did not understand how this can be set from this Java program. 但是,我不明白如何从此Java程序中进行设置。 Can someone please provide some help? 有人可以提供帮助吗?
Project dir: /Users/eclipsews/PythonJava
Exception in thread "main" ImportError: No module named Building
Hi found the answer to this issue! 您好找到了这个问题的答案!
Added the PySystemState.initialize method where I explicitly provide the "python.path" property, which is initialized to my project's path, where python modules are available. 添加了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 );
This produces the correct output as follows: 这将产生正确的输出,如下所示:
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.