5

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.

2
  • 1
    @wRAR: Because "os = 'sys'; import os" tries to import os, not sys. Commented Apr 11, 2010 at 16:31
  • Why do you want to check rather than just importing the modules and letting the default mechanism do its thing? Commented Apr 11, 2010 at 16:49

4 Answers 4

10

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!-)

Sign up to request clarification or add additional context in comments.

Comments

3

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'>
>>>

Comments

0

Nowadays, more than 10 years after the question, in Python >= 3.4, the way to go is using importlib.util.find_spec:

import importlib
spec = importlib.util.find_spec('path.to.module')
if spam:
    print('module can be imported')

This mechanism is them preferred over imp.find_module:

import importlib.util
import sys


# this is optional set that if you what load from specific directory
moduledir="d:\\dirtest"

```python
try:
    spec = importlib.util.find_spec('path.to.module', moduledir)
    if spec is None:
        print("Import error 0: " + " module not found")
        sys.exit(0)
    toolbox = spec.loader.load_module()
except (ValueError, ImportError) as msg:
    print("Import error 3: "+str(msg))
    sys.exit(0)

print("load module")

For old Python versions also look how to check if a python module exists without importing it

Comments

0

In recent Python versions (>= 3.4), importlib.util.module_from_spec('foo') will return None if foo cannot be imported, in other words, unavilable. This check will not actually import the module.

import importlib.util
if importlib.util.find_spec('foo') is None:
    # module foo cannot be imported
    pass
else:
    # module foo can be imported
    pass

More info:

  1. importlib.util.module_from_spec documentation
  2. Sample code to import a module after checking that 1) it has not been imported yet; and 2) it can be imported.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.