views:

86

answers:

2

given a list of module names (e.g. mymods = ['numpy', 'scipy', ...]) how can I check if the modules are available?

I tried the following but it's incorrect:

for module_name in mymods:
  try:
    import module_name
  except ImportError:
    print "Module %s not found." %(module_name)

thanks.

+3  A: 

Use the __import__ function:

>>> for mname in ('sys', 'os', 're'): __import__(mname)
...
<module 'sys' (built-in)>
<module 'os' from 'C:\Python\lib\os.pyc'>
<module 're' from 'C:\Python\lib\re.pyc'>
>>>
Vinay Sajip
+8  A: 

You could use both the __import__ function, as in @Vinay's answer, and a try/except, as in your code:

for module_name in mymods:
  try:
    __import__(module_name)
  except ImportError:
    print "Module %s not found." %(module_name)

Alternatively, to just check availability but without actually loading the module, you can use standard library module imp:

import imp
for module_name in mymods:
  try:
    imp.find_module(module_name)
  except ImportError:
    print "Module %s not found." %(module_name)

this can be substantially faster if you do only want to check for availability, not (yet) load the modules, especially for modules that take a while to load. Note, however, that this second approach only specifically checks that the modules are there -- it doesn't check for the availability of any further modules that might be required (because the modules being checked try to import other modules when they load). Depending on your exact specs, this might be a plus or a minus!-)

Alex Martelli