Để kiểm tra xem có thể import module gì đó trong Python 2, bạn có thể dùng module imp với try...except. Ví dụ:
import imp
try:
imp.find_module('eggs')
found = True
except ImportError:
found = False
print found
Kết quả:
False
Bạn cũng có thể dùng iter_modules từ module pkgutil để lặp qua tất cả module và tìm module chỉ định. Ví dụ:
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')
Kết quả:
True
Điều này là do module này đã được cài trên máy của tôi.
Hoặc nếu chỉ muốn kiểm tra trong shell, có thể dùng:
python -c "help('modules');" | grep yourmodule