14

I am writing a package in python that talks to an ldap server. I want it to work in CPython and Jython. To get it to work with CPython, I have successfully coded against python-ldap. However, to get it working with Jython, I must use a java jar.

How can I distribute the jar file with my package, so that if it can "import java", it knows its jython, and dynamically adds the java jar to the path, and utilizies it. However, if that fails, it knows its CPython and uses the python-ldap libraries.

Any ideas?

gregturn
  • 2,625
  • 3
  • 25
  • 40

1 Answers1

26

Just add your jar to sys.path, like this:

~ $ jython
Jython 2.5.0+ (trunk:6691, Aug 17 2009, 17:09:38) 
[Java HotSpot(TM) Client VM (Apple Computer, Inc.)] on java1.6.0-dp
Type "help", "copyright", "credits" or "license" for more information.
>>> from org.thobe.somepackage import SomeClass # not possible to import yet
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named thobe
>>> import sys
>>> sys.path.append("/var/javalib/some-thobe-package.jar") # add the jar to your path
>>> from org.thobe.somepackage import SomeClass # it's now possible to import the package
>>> some_object = SomeClass() # You can now use your java class

It couldn't get more simple than that :)

In your case you probably want to use the path of your package to find the jar:

# yourpackage/__init__.py

import sys, os
if 'java' in sys.platform.lower():
    sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                 "your-lib.jar"))
    from jython_implementation import library
else:
    from cpython_implementation import library

Hope that helps!

thobe
  • 1,573
  • 1
  • 11
  • 9
  • Unclear how "from org.thobe.somepackage import SomeClass" is based off of the name of the package "some-thobe-package". I gather that you need "from org." but how does "some-thobe-package.jar" translate to "thobe.somepackage" on the import? – carl crott Feb 12 '12 at 09:50
  • @delinquentme Since the jar file is in the path, its internal structure is what is referenced. If you were to run`jar -xvf /var/javalib/some-thobe-package.jar` You would see that the structure would be org/thobe/somepackage/SomeClass.class – fernferret Mar 13 '12 at 19:09
  • This locks jar files (cannot be deleted). Is it possible for jython to unlock these files after they are not needed? – deckard cain Apr 09 '17 at 18:41