Search code examples
pythonreflectionimportmodulepython-module

Test for Python module dependencies being installed


How could one test whether a set of modules is installed, given the names of the modules. E.g.

modules = set(["sys", "os", "jinja"])

for module in modules:
  # if test(module exists):
  #   do something

While it's possible to write out the tests as:

try:
  import sys
except ImportError:
  print "No sys!"

This is a bit cumbersome for what I'm doing. Is there a dynamic way to do this?

I've tried eval("import %s"%module) but that complained of a compile error.

I'm grateful for your thoughts and suggestions. Thank you.


Solution

  • You can use the __import__() function like this::

    for module in modules:
        try:
            __import__(module)
        except ImportError:
            do_something()
    

    You can also use imp.find_module to determine whether a module can be found without importing it::

    import imp
    for module in modules:
        try:
            imp.find_module(module)
        except ImportError:
            do_something()
    

    Oh, and the reason you can't use eval() is because import is a statement, not an expression. You can use exec if you really want to, though I wouldn't recommend it::

    for module in modules:
        try:
            exec 'import ' + module
        except ImportError:
            do_something()