如何检查Python模块是否存在并且可以导入
我正在使用调试工具栏和Django框架,想要在项目中添加它,但需要满足两个条件:
settings.DEBUG
的值是True
- 模块本身存在
第一个条件不难满足。
# adding django debug toolbar
if DEBUG:
MIDDLEWARE_CLASSES += 'debug_toolbar.middleware.DebugToolbarMiddleware',
INSTALLED_APPS += 'debug_toolbar',
但是,我该如何检查模块是否存在呢?
我找到了一种解决方案:
try:
import debug_toolbar
except ImportError:
pass
但由于在Django的其他地方会进行导入,我需要使用if/else逻辑来检查模块是否存在,这样我才能在settings.py中进行检查。
def module_exists(module_name):
# ??????
# adding django debug toolbar
if DEBUG and module_exists('debug_toolbar'):
MIDDLEWARE_CLASSES += 'debug_toolbar.middleware.DebugToolbarMiddleware',
INSTALLED_APPS += 'debug_toolbar',
有没有办法做到这一点呢?
1 个回答
47
你可以在你的函数里面使用相同的逻辑:
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
return True
这个解决方案不会影响性能,因为模块只会被导入一次。