Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tìm module Python nào đang được import từ package

Để tìm tất cả module Python từ package cụ thể đang dùng trong ứng dụng, dùng dict sys.modules. sys.modules là dictionary map tên module đến module. Xem keys để biết module đã import.

Ví dụ:

>>> from datetime import datetime
>>> import sys
>>> print sys.modules.keys()
['copy_reg', 'sre_compile', 'locale', '_sre', 'functools', 'encodings', 'site', '__builtin__', 'datetime', 'sysconfig', 'operator', '__main__', 'types', 'encodings.encodings', 'abc', 'encodings.cp437', '_weakrefset', 'errno', 'encodings.codecs', 'backports', 'sre_constants', 're', '_abcoll', 'ntpath', '_codecs', 'zope', 'nt', '_warnings', 'genericpath', 'stat', 'zipimport', 'encodings.__builtin__', 'mpl_toolkits', 'warnings', 'UserDict', 'encodings.cp1252', 'sys', 'codecs', 'os.path', '_functools', '_locale', 'signal', 'traceback', 'linecache', 'encodings.aliases', 'exceptions', 'sre_parse', 'os', '_weakref']

Cũng có thể dùng python -v, sẽ emit message về mọi module import. Ví dụ, nếu code Python trong hello.py:

$ python -v hello.py