Setting the import module path in Jython - strange behavior

I am creating Java for the Jython bridge class. The task I'm trying to solve is to get Jython to look for python modules in my application working directory (also known as the program execution directory).

I do this by adding the value of System.getProperty("user.dir") to 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); 

I get an ImportError exception:

 python module 'user_module' was not found. sys.path: ['<other jars>\\Lib', '/<path to jython>/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) ... 

Where C:\\Users\\vvlad\\IDEAProjects\\transform is the application directory.

In sys.path it looks like this:

Import works fine when I manually specify the full path to the working directory in the python.path variable of the Jython registry. And sys.path looks different:

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

Thus, the import works fine when the working directory is in the first entry in sys.path . But it does not work when the working directory is the last entry.

I use Jython 2.5.2 and run tests on a Windows machine from IntelliJ IDEA.

Plan B for me was to set the Jython python.path registry with user.dir value before initializing PySysState - but this will lead to some hidden behavior.

+4
source share
1 answer

Here is the code to set the python.path registry value with user.dir in your code (plan B, which I mentioned in the question):

This is how you initialize PySysState:

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

setDefaultPythonPath method:

 /** * 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; } 
+2
source

All Articles