Checking the software availability of a module in Python?

Given a list of module names (for example, mymods = ['numpy', 'scipy', ...]), how can I check if modules are available?

I tried the following, but this is not true:

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

thanks.

+4
source share
2 answers

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

+9
source

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'> >>> 
+3
source

Source: https://habr.com/ru/post/1306616/


All Articles