Checking for module availability programmatically in Python?
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 I开发者_Python百科mportError:
print "Module %s not found." %(module_name)
thanks.
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!-)
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'>
>>>
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
精彩评论