Computer >> Máy Tính >  >> Lập trình >> Python

Làm cách nào để tìm mô-đun Python nào đang được nhập từ một gói?


Để tìm tất cả các mô-đun python từ một gói cụ thể đang được sử dụng trong một ứng dụng, bạn có thể sử dụng sys.modules dict. sys.modules là một từ điển ánh xạ tên mô-đun thành các mô-đun. Bạn có thể kiểm tra các khóa của nó để xem các mô-đun đã nhập.

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']

Bạn cũng có thể sử dụng python -v, nó sẽ phát ra thông báo về mọi mô-đun được nhập. Ví dụ:nếu bạn có mã python trong hello.py, thì

$ python -v hello.py