如何在不导入的情况下检查python模块是否存在?
要检查是否可以在Python2中导入内容,可以将imp模块与try...except一起使用。例如,
import imp
try:
imp.find_module('eggs')
found = True
except ImportError:
found = False
print found这将为您提供输出:
False
您还可以使用pkgutil模块中的iter_modules遍历所有模块,以查找指定的模块是否存在。例如,
from pkgutil import iter_modules
def module_exists(module_name):
return module_name in (name for loader, name, ispkg in iter_modules())
print module_exists('scrapy')这将给出输出:
True
这是因为此模块已安装在我的PC上。
或者,如果您只想在外壳中检查它,则可以使用,
python -c "help('modules');" | grep yourmodule热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短