How can I add jars dynamically to jython, inside script?

后端 未结 1 532
花落未央
花落未央 2020-12-24 15:13

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 pyt

相关标签:
1条回答
  • 2020-12-24 15:59

    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!

    0 讨论(0)
提交回复
热议问题