在Python中以编程方式检查模块可用性?

时间:2010-04-11 16:20:47

标签: python module python-module

给出模块名称列表(例如mymods = ['numpy','scipy',...])如何检查模块是否可用?

我尝试了以下但是不正确:

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

感谢。

3 个答案:

答案 0 :(得分:9)

您可以同时使用__import__功能,如@ Vinay的回答, a try / except,如代码所示:

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

或者,要只是检查可用性,但没有实际加载模块,您可以使用标准库模块imp

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

如果你只想检查可用性,而不是(还)加载模块,这可能会大大加快,特别是对于需要一段时间才能加载的模块。但请注意,第二种方法仅专门检查模块是否存在 - 它不检查可能需要的任何其他模块的可用性(因为正在检查的模块尝试{ {1}}其他模块加载时)。根据您的确切规格,这可能是加号或减号! - )

答案 1 :(得分:3)

使用__import__功能:

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

答案 2 :(得分:0)

如今,在提出问题 10 多年后,在 Python >= 3.4 中,要走的路是使用 importlib.util.find_spec

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

这个机制就是他们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")

对于旧的 Python 版本,也可以查看 how to check if a python module exists without importing it