3

I must admit that I'm slightly confused by the Jython import logic.

I now that I can manually add the jars one by one to sys.path but I have a whole bunch of them and this is quite painful.

Adding the directory containing the jars obviously doesn't work.

What is the best way to do that?

Cedric H.
  • 7,980
  • 10
  • 55
  • 82

3 Answers3

7

The following code should do the trick for you and limit the amount of typing that you need to do while making use of the standard jython library.

import os,glob,sys

directories=['/path/to/jars/','/different/path/to/more/jars/']

for directory in directories:
    for jar in glob.glob(os.path.join(directory,'*.jar')):
        sys.path.append(jar)

Better answer: You can create a .pth file in the jython site-packages and include within it all of the full paths to the jars you want included on the path. Here is what I did to include poi jars(contents of .pth file):

/home/kris/jython2.5.3/poi-3.11/poi-3.11-20141221.jar
/home/kris/jython2.5.3/poi-3.11/poi-ooxml-3.11-20141221.jar
/home/kris/jython2.5.3/poi-3.11/poi-ooxml-schemas-3.11-20141221.jar
/home/kris/jython2.5.3/poi-3.11/ooxml-lib/xmlbeans-2.6.0.jar

After doing that I can then import without having to append to path:

from org.apache.poi.xssf.usermodel import XSSFWorkbook
khammel
  • 2,047
  • 1
  • 14
  • 18
2
import sys
sys.path.append("/var/javalib/some-name-package.jar") # add the jar to your path
from org.somename.somepackage import SomeClass # it's now possible to import the package
some_object = SomeClass() # You can now use your java class

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
Archit Garg
  • 1,012
  • 8
  • 16
1

Depends quite a bit on how you are running Jython. One very simple way (if applicable) is to put them on the Java boot classpath before running jython

java -cp "lib/*" jython.jar <arguments>
Eero Aaltonen
  • 4,239
  • 1
  • 29
  • 41