如何在不导入的情况下检查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