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