python如何查看导入模块,如何检查python模块是否存在并可以导入

I am using debug toolbar with django and would like to add it to project if two conditions are true:

settings.DEBUG is True

module itself exists

It's not hard to do the first one

# adding django debug toolbar

if DEBUG:

MIDDLEWARE_CLASSES += 'debug_toolbar.middleware.DebugToolbarMiddleware',

INSTALLED_APPS += 'debug_toolbar',

But how do I check if module exists?

I have found this solution:

try:

import debug_toolbar

except ImportError:

pass

But since import happens somewhere else in django, I need if/else logic to check if module exists, so I can check it in 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',

Is there a way to do it?

解决方案

You can use the same logic inside your function:

def module_exists(module_name):

try:

__import__(module_name)

except ImportError:

return False

else:

return True

There is no performance penalty to this solution becuase modules are imported only once.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值