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

发布于 2024-08-28 15:01:47 字数 256 浏览 4 评论 0原文

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

我尝试了以下方法,但这是不正确的:

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

谢谢。

given a list of module names (e.g. mymods = ['numpy', 'scipy', ...]) how can I check if the modules are available?

I tried the following but it's incorrect:

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

thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

新人笑 2024-09-04 15:01:47

您可以使用 __import__ 函数,如 @Vinay 的答案,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)

如果您想做只想检查可用性,而不是检查可用性,这会快得多(还)加载模块,特别是那些需要一段时间才能加载的模块。但请注意,第二种方法仅专门检查模块是否存在 - 它不会检查可能需要的任何其他模块的可用性(因为正在检查的模块尝试<代码>导入其他模块加载时)。根据您的具体规格,这可能是一个优点或缺点!-)

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

-黛色若梦 2024-09-04 15:01:47

使用 __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'>
>>>

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'>
>>>
肤浅与狂妄 2024-09-04 15:01:47

如今,在问题提出 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 模块无需导入即可存在

Nowadays, more than 10 years after the question, in Python >= 3.4, the way to go is using importlib.util.find_spec:

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

This mechanism is them 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")

For old Python versions also look how to check if a python module exists without importing it

眼睛会笑 2024-09-04 15:01:47

在最近的 Python 版本 (>= 3.4) 中,如果无法导入 fooimportlib.util.module_from_spec('foo') 将返回 None ,换句话说,不可用。
此检查不会实际导入模块。

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)可以进口。

In recent Python versions (>= 3.4), importlib.util.module_from_spec('foo') will return None if foo cannot be imported, in other words, unavilable.
This check will not actually import the module.

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

More info:

  1. importlib.util.module_from_spec documentation
  2. Sample code to import a module after checking that 1) it has not been imported yet; and 2) it can be imported.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文