CPython如何实现os.environ?

7 python windows python-3.x python-internals

我正在查看源代码,注意到它environ在定义之前在方法中引用了一个变量:

def _createenviron():
    if name == 'nt':
        # Where Env Var Names Must Be UPPERCASE
        def check_str(value):
            if not isinstance(value, str):
                raise TypeError("str expected, not %s" % type(value).__name__)
            return value
        encode = check_str
        decode = str
        def encodekey(key):
            return encode(key).upper()
        data = {}
        for key, value in environ.items():
            data[encodekey(key)] = value
    else:
        # Where Env Var Names Can Be Mixed Case
        encoding = sys.getfilesystemencoding()
        def encode(value):
            if not isinstance(value, str):
                raise TypeError("str expected, not %s" % type(value).__name__)
            return value.encode(encoding, 'surrogateescape')
        def decode(value):
            return value.decode(encoding, 'surrogateescape')
        encodekey = encode
        data = environ
    return _Environ(data,
        encodekey, decode,
        encode, decode)

# unicode environ
environ = _createenviron()
del _createenviron
Run Code Online (Sandbox Code Playgroud)

那么如何environ设置呢?我似乎无法推理它的初始化和声明位置以便_createenviron可以使用它?

And*_*lov 2

TLDR 搜索from posix import *模块os内容。

该模块从 . 开头的(Unix) 或(Windows) 低级模块os导入所有公共符号。posixntos.py

posix公开environ为普通 Python dict。 用类似字典的对象os包装它,该对象更新项目更改时的环境变量。_Environ_Environ