在Jython中设置导入模块路径 – 奇怪的行为

我正在构建Java到Jython桥类。 我正在尝试解决的任务是让Jython在我的应用程序工作目录(也称为程序执行目录)中查找python模块。

我是通过将System.getProperty("user.dir")值附加到sys.path来实现的:

 pySysState = new PySystemState(); //add working directory into sys.path pySysState.path.append(new PyString(System.getProperty("user.dir"))); log_.info("Jython sys state initialized. sys.path: " + this.pySysState.path); 

我得到ImportErrorexception:

 python module 'user_module' was not found. sys.path: ['\\Lib', '//Lib', '__classpath__', '__pyclasspath__/', 'C:\\Users\\vvlad\\IDEAProjects\\transform'] ImportError: No module named scheduled_helper at org.python.core.Py.ImportError(Py.java:290) at org.python.core.imp.import_first(imp.java:750) at org.python.core.imp.import_name(imp.java:834) ... 

其中C:\\Users\\vvlad\\IDEAProjects\\transform是应用程序目录。

sys.path看起来像这样:

当我在Jython注册表python.path变量中手动指定工作目录的完整路径时,导入工作正常。 sys.path看起来不同:

 >>sys.path: ['C:\\Users\\vvlad\\IDEAProjects\\transform', '\\Lib', '//jython-2.5.2.jar/Lib', '__classpath__', '__pyclasspath__/', ] 

因此,当工作目录作为sys.path的第一个条目时,导入工作正常。 但是当工作目录是最后一个条目时失败。

我正在使用Jython 2.5.2并在IntelliJ IDEA环境中的Windows机器上运行测试。

对我来说,B计划是在初始化PySysState之前使用user.dir值设置Jython注册表python.path – 但这会引入一些隐藏的行为。

以下是在代码中使用user.dir设置注册表python.path值的代码(问题中提到的Plan BI):

以下是初始化PySysState的方法:

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

setDefaultPythonPath方法:

 /** * Adds user.dir into python.path to make Jython look for python modules in working directory in all cases * (both standalone and not standalone modes) * @param props * @return props */ private Properties setDefaultPythonPath(Properties props) { String pythonPathProp = props.getProperty("python.path"); String new_value; if (pythonPathProp==null) { new_value = System.getProperty("user.dir"); } else { new_value = pythonPathProp +java.io.File.pathSeparator + System.getProperty("user.dir") + java.io.File.pathSeparator; } props.setProperty("python.path",new_value); return props; }