如何在不导入的情况下检查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热门推荐
1 带清的简短祝福语
2 修祖屋祝福语简短
8 短祝福语简短暖心
10 给孙子拜年祝福语简短
11 圣诞祝福语简短文字
12 祝福语简短古诗词
13 过年爱情祝福语大全简短
14 对疫情的简短祝福语
15 老师对学校祝福语简短
16 生日祝福语大全女孩简短
17 信耶稣的人祝福语简短
18 20岁简短生日祝福语