python.sys.modules模块

sys.modules是一个全局字典,该字典是python启动后就加载在内存中。每当程序员导入新的模块,sys.modules都将记录这些模块。字典sys.modules对于加载模块起到了缓冲的作用。当某个模块第一次导入,字典sys.modules将自动记录该模块。当第二次再导入该模块时,python会直接到字典中查找,从而加快了程序运行的速度。

字典sys.modules具有字典所拥有的一切方法,可以通过这些方法了解当前的环境加载了哪些模块

import sys
print(sys.modules[__name__])
print(sys.modules.values())
print(sys.modules.keys())
print(sys.modules.items())

执行结果

>>> import sys
>>> print(sys.modules[__name__])

>>> print(sys.modules.values())
dict_values([, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ])
>>> print(sys.modules.keys())
dict_keys(['builtins', 'sys', '_frozen_importlib', '_imp', '_warnings', '_thread', '_weakref', '_frozen_importlib_external', '_io', 'marshal', 'posix', 'zipimport', 'encodings', 'codecs', '_codecs', 'encodings.aliases', 'encodings.utf_8', '_signal', '__main__', 'encodings.latin_1', 'io', 'abc', '_weakrefset', 'site', 'os', 'errno', 'stat', '_stat', 'posixpath', 'genericpath', 'os.path', '_collections_abc', '_sitebuiltins', 'sysconfig', '_sysconfigdata_m_linux_x86_64-linux-gnu', '_bootlocale', '_locale', 'types', 'functools', '_functools', 'collections', 'operator', '_operator', 'keyword', 'heapq', '_heapq', 'itertools', 'reprlib', '_collections', 'weakref', 'collections.abc', 'importlib', 'importlib._bootstrap', 'importlib._bootstrap_external', 'warnings', 'importlib.util', 'importlib.abc', 'importlib.machinery', 'contextlib', 'mpl_toolkits', 'sphinxcontrib', 'readline', 'atexit', 'rlcompleter'])
>>> print(sys.modules.items())
dict_items([('builtins', ), ('sys', ), ('_frozen_importlib', ), ('_imp', ), ('_warnings', ), ('_thread', ), ('_weakref', ), ('_frozen_importlib_external', ), ('_io', ), ('marshal', ), ('posix', ), ('zipimport', ), ('encodings', ), ('codecs', ), ('_codecs', ), ('encodings.aliases', ), ('encodings.utf_8', ), ('_signal', ), ('__main__', ), ('encodings.latin_1', ), ('io', ), ('abc', ), ('_weakrefset', ), ('site', ), ('os', ), ('errno', ), ('stat', ), ('_stat', ), ('posixpath', ), ('genericpath', ), ('os.path', ), ('_collections_abc', ), ('_sitebuiltins', ), ('sysconfig', ), ('_sysconfigdata_m_linux_x86_64-linux-gnu', ), ('_bootlocale', ), ('_locale', ), ('types', ), ('functools', ), ('_functools', ), ('collections', ), ('operator', ), ('_operator', ), ('keyword', ), ('heapq', ), ('_heapq', ), ('itertools', ), ('reprlib', ), ('_collections', ), ('weakref', ), ('collections.abc', ), ('importlib', ), ('importlib._bootstrap', ), ('importlib._bootstrap_external', ), ('warnings', ), ('importlib.util', ), ('importlib.abc', ), ('importlib.machinery', ), ('contextlib', ), ('mpl_toolkits', ), ('sphinxcontrib', ), ('readline', ), ('atexit', ), ('rlcompleter', )])
>>>

你可能感兴趣的:(python.sys.modules模块)