Python模块导入之sys.modules

python中的sys.modules是一个全局字典,从python程序启动就加载到了内存,用于保存当前已导入(加载)的所有模块名和模块对象。在python的模块查找中,sys.modules起到缓存作用,避免了模块的重复加载。

程序在导入某个模块时,会首先查找sys.modules中是否包含此模块名,若存在,则只需将模块的名字加入到当前模块的Local名字空间中;若不存在,则需要从sys.path目录中按照模块名称查找模块文件,模块文件可以是py、pyc、pyd,找到后将模块加载到内存,并加入到sys.modules字典,最后将模块的名字加入当前模块的Local名字空间中。

下面代码演示了导入模块后,sys.modulels中的键值变化

import sys

modules1 = sys.modules.copy()
for key, value in modules1.items():
    print('"{}": "{}"'.format(key, value))

import logging
modules2 = sys.modules.copy()
print('首次导入logging模块后在sys.modules中加入的模块名:', modules2.keys() - modules1.keys())

import logging
modules3 = sys.modules
print('再次导入logging模块后在sys.modules中加入的模块名:', modules3.keys() - modules2.keys())
"sys": "<module 'sys' (built-in)>"
"builtins": "<module 'builtins' (built-in)>"
"_frozen_importlib": "<module 'importlib._bootstrap' (frozen)>"
"_imp": "<module '_imp' (built-in)>"
"_thread": "<module '_thread' (built-in)>"
"_warnings": "<module '_warnings' (built-in)>"
"_weakref": "<module '_weakref' (built-in)>"
"zipimport": "<module 'zipimport' (built-in)>"
"_frozen_importlib_external": "<module 'importlib._bootstrap_external' (frozen)>"
"_io": "<module 'io' (built-in)>"
"marshal": "<module 'marshal' (built-in)>"
"nt": "<module 'nt' (built-in)>"
"winreg": "<module 'winreg' (built-in)>"
"encodings": "<module 'encodings' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\encodings\\__init__.py'>"
....................................
"codecs": "<module 'codecs' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\codecs.py'>"
"_codecs": "<module '_codecs' (built-in)>"

首次导入logging模块后在sys.modules中加入的模块名: {'token', 'collections.abc', 'sre_compile', 'weakref', 'copyreg', 're', 'traceback', 'atexit', 'sre_parse', 'string', 'linecache', '_weakrefset', '_string', 'tokenize', 'sre_constants', 'threading', '_sre', 'time', 'logging', 'enum'}
再次导入logging模块后在sys.modules中加入的模块名: set()

在flask源码中就利用了sys.modules来帮助获取应用的根目录,涉及代码如下

def get_root_path(import_name):
    """Returns the path to a package or cwd if that cannot be found.  This
    returns the path of a package or the folder that contains a module.

    Not to be confused with the package path returned by :func:`find_package`.
    """
    # Module already imported and has a file attribute.  Use that first.
    mod = sys.modules.get(import_name) # 根据模块名获取到模块对象
    if mod is not None and hasattr(mod, '__file__'): # C写的模块没有__file__属性
        return os.path.dirname(os.path.abspath(mod.__file__))
    ......
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值