9 September, 2009 - 11:07

For some small tools or jobs I use Jython so I can (re)use some existing Java code, while still writing in Python. I also have various custom Python modules, of which I put the paths in my PYTHONPATH environment variable, so those modules are easily available in Python scripts and interactive sessions.

However, Jython does not automatically pick up the PYTHONPATH information, for reasons that seem to be discussed in this Jython development mailing list thread.

Jython 2.5 introduced the JYTHONPATH environmental variable as Jython-equivalent of PYTHONPATH, so setting both to the same value should do the trick for most use cases (unless you're working in a setup with incompatible Python an Jython versions).

For Jython versions prior to 2.5 (like 2.2.1 in my case), there is an easy "workaround", by invoking Jython with the appropriate -Dpython.path=foo/path:bar/path option. For example as follows:

jython -Dpython.path=$PYTHONPATH

To make it a bit less clunky, I added the following alias to my bash aliases:

alias jython='jython -Dpython.path=$PYTHONPATH'

Note that I used single quotes in the alias. This way, $PYTHONPATH is not expanded before defining the alias, but on invocation of the jython command. This means that changes to the PYTHONPATH environmental variable happening after defining the alias (which typically happens when starting a new shell) will still be picked up in the alias command.
If I had used double quotes, $PYTHONPATH would be expanded before defining the alias, which means that -Dpython.path would be hardcoded. Consequently, changes to PYTHONPATH would be invisible for the jython alias.