如何檢查一個 python 模組是否存在?而不匯入它?
要在 Python 2 中檢查是否可以匯入某個模組,可以使用 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
這是因為我的電腦上安裝了這個模組。
也可以在 shell 中使用以下方法:
python -c "help('modules');" | grep yourmodule
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP