我需要知道是否存在python模块,而不导入它.
导入可能不存在的东西(不是我想要的东西):
try:
import eggs
except ImportError:
pass
Run Code Online (Sandbox Code Playgroud) 我正在使用django的调试工具栏,如果两个条件为真,我想将它添加到项目中:
settings.DEBUG 是 True做第一个并不难
# adding django debug toolbar
if DEBUG:
MIDDLEWARE_CLASSES += 'debug_toolbar.middleware.DebugToolbarMiddleware',
INSTALLED_APPS += 'debug_toolbar',
Run Code Online (Sandbox Code Playgroud)
但是如何检查模块是否存在?
我找到了这个解决方案:
try:
import debug_toolbar
except ImportError:
pass
Run Code Online (Sandbox Code Playgroud)
但由于导入发生在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',
Run Code Online (Sandbox Code Playgroud)
有办法吗?