如何在不匯入的情況檢查python模組是否存在?


要檢查你是否可以在Python 2中匯入某些東西,你可以使用帶try…except的imp模組。例如,

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

更新於: 01-Oct-2019

867瀏覽量

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.