You can use both __import__ functions, 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 simply check for availability, but without actually loading the module, you can use the 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 significantly faster if you only want to check for availability and not load modules, especially for modules that take time to load. Please note, however, that this second approach only specifically checks for the presence of modules - it does not check for any additional modules that may be required (since the modules being tested try to import other modules at boot time). Depending on your specific characteristics, this can be a plus or a minus! -)
source share