如何檢查一個 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

更新於:2019 年 10 月 1 日

867 次瀏覽

啟動你的職業發展之路

完成課程獲得認證

開始
廣告
© . All rights reserved.