Home » Python » Jython: Determine what Python libraries are available in a system for import-Exceptionshub

Jython: Determine what Python libraries are available in a system for import-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

In IBM’s Maximo 7.6.1.1, it is possible to write automation scripts with Jython 2.7.0.

Using Jython, I want to determine what Python libraries are available in the system for import.

For instance, I can import the math and os libraries, but I can’t import the json library (because it hasn’t been added to the system).

  • It is not possible for me to add additional Python libraries to the system; this is locked down and is out of my control.

  • There doesn’t seem to be a rhyme or reason as to which Python libraries have been included in Maximo, and which ones haven’t (it doesn’t seem to align with the Standard Python Library).

  • The documentation and IBM support have been of zero help.

Is there a way to determine what Python libraries are available for import — via a Jython script?

Example: print list_of_importable_libraries()

How to&Answers:
import pip
installed_packages = pip.get_installed_distributions()
installed_packages_list = sorted(["%s==%s" % (i.key, i.version)
     for i in installed_packages])
print(installed_packages_list)

As a (too long) one liner:

sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])

Possible error:

AttributeError: ‘pip’ has no attribute ‘get_installed_distributions’

For pip == 10.0.0

You can downgrade pip to >= 9.0.0 to fix this
And a possible duplicate of this quesstion.