我如何知道Python模块是否存在,而不导入它?
导入一些可能不存在(不是我想要的)的东西会导致:
try:
import eggs
except ImportError:
pass
我如何知道Python模块是否存在,而不导入它?
导入一些可能不存在(不是我想要的)的东西会导致:
try:
import eggs
except ImportError:
pass
当前回答
在使用yarbelk的响应后,我做了这个,所以我不需要导入ìmp。
try:
__import__('imp').find_module('eggs')
# Make things with a supposed existing module
except ImportError:
pass
例如,它在Django的settings.py文件中就很有用。
其他回答
没有任何方法可以在不导入其父包的情况下可靠地检查“虚线模块”是否可导入。说到这里,对于“如何检查Python模块是否存在”这个问题,有很多解决方案。
下面的解决方案解决了导入的模块即使存在也会引发ImportError的问题。我们希望将这种情况与模块不存在的情况区分开来。
Python 2:
import importlib
import pkgutil
import sys
def find_module(full_module_name):
"""
Returns module object if module `full_module_name` can be imported.
Returns None if module does not exist.
Exception is raised if (existing) module raises exception during its import.
"""
module = sys.modules.get(full_module_name)
if module is None:
module_path_tail = full_module_name.split('.')
module_path_head = []
loader = True
while module_path_tail and loader:
module_path_head.append(module_path_tail.pop(0))
module_name = ".".join(module_path_head)
loader = bool(pkgutil.find_loader(module_name))
if not loader:
# Double check if module realy does not exist
# (case: full_module_name == 'paste.deploy')
try:
importlib.import_module(module_name)
except ImportError:
pass
else:
loader = True
if loader:
module = importlib.import_module(full_module_name)
return module
Python 3:
import importlib
def find_module(full_module_name):
"""
Returns module object if module `full_module_name` can be imported.
Returns None if module does not exist.
Exception is raised if (existing) module raises exception during its import.
"""
try:
return importlib.import_module(full_module_name)
except ImportError as exc:
if not (full_module_name + '.').startswith(exc.name + '.'):
raise
在使用yarbelk的响应后,我做了这个,所以我不需要导入ìmp。
try:
__import__('imp').find_module('eggs')
# Make things with a supposed existing module
except ImportError:
pass
例如,它在Django的settings.py文件中就很有用。
使用pkgutil中的一个函数,例如:
from pkgutil import iter_modules
def module_exists(module_name):
return module_name in (name for loader, name, ispkg in iter_modules())
Ask Ubuntu的一个更简单的if语句,如何检查Python中是否安装了一个模块?:
import sys
print('eggs' in sys.modules)
你也可以使用importlib。util直接
import importlib.util
def module_exists_without_import(module_name):
spec = importlib.util.find_spec(module_name)
return spec is not None