Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ตรวจสอบว่าโมดูล Python มีอยู่จริงหรือไม่ (โดยไม่ Import)

มีหลายวิธีตรวจสอบว่าโมดูลสามารถ Import ได้หรือไม่ โดยไม่ต้อง Import จริง

วิธีที่ 1: ใช้ imp.find_module (Python 2/3.3-)

import imp
try:
    imp.find_module('eggs')
    found = True
except ImportError:
    found = False
print(found)  # False

วิธีที่ 2: ใช้ 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 ถ้าติดตั้งไว้

วิธีที่ 3: ตรวจสอบจาก Command Line

python -c "help('modules');" | grep yourmodule

Python 3.4+ แนะนำใช้ importlib.util.find_spec

import importlib.util
spec = importlib.util.find_spec("module_name")
if spec is not None:
    print("Module exists")