Importing jars from Jython

大兔子大兔子 提交于 2020-01-01 06:40:09

问题


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?


回答1:


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



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



回答3:


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>


来源:https://stackoverflow.com/questions/31811809/importing-jars-from-jython

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