Importing jars from Jython

白昼怎懂夜的黑 提交于 2019-12-03 17:29:05

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
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

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>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!