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

问题描述 投票:0回答:4

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

我尝试了以下但不正确:

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

谢谢。

python module python-module
4个回答
10
投票

您可以使用

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

如果您do只想检查可用性,而不是(还)加载模块,特别是对于需要一段时间加载的模块,这会快得多。但请注意,第二种方法仅专门检查模块是否存在——它不会检查可能需要的任何其他模块的可用性(因为正在检查的模块会尝试

import
其他模块)他们加载)。根据您的具体规格,这可能是一个优点或缺点!-)


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

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

这个机制是他们优先于

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 版本,还可以查看 如何检查 python 模块是否存在而不导入它


0
投票

在最近的 Python 版本(>= 3.4)中,如果

importlib.util.module_from_spec('foo')
无法导入(即不可用),
None
将返回
foo
。 此检查不会实际导入模块。

import importlib.util
if importlib.util.find_spec('foo') is None:
    # module foo cannot be imported
    pass
else:
    # module foo can be imported
    pass

更多信息:

  1. importlib.util.module_from_spec
    文档
  2. 示例代码,用于在检查 1) 尚未导入后导入模块; 2)可以导入。
© www.soinside.com 2019 - 2024. All rights reserved.