os.environ 在哪里初始化?

发布于 2024-08-16 19:29:00 字数 257 浏览 3 评论 0原文

使用此代码,会输出许多键,但我期望没有输出:

import os

for i in os.environ:
    print  i

这是来自 os.py 的代码:

try:
    environ
except NameError:
    environ = {}

os.environ 从哪里获取其值? 它在哪里初始化?

Using this code, many keys are output, but I expected no output:

import os

for i in os.environ:
    print  i

This is the code from os.py:

try:
    environ
except NameError:
    environ = {}

Where does os.environ get its values from? Where is it initialized?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

℡寂寞咖啡 2024-08-23 19:29:00

os 模块首先从特定于平台的子模块(例如 _nt_posix)导入所有名称,然后进行一些标准化。显然,environ 名称(代表系统环境)是由特定于平台的子模块定义的(正如通常预期的那样!!!),因此 os.py 中的 except 子句没有触发,而 os.environ 只是通常应该的丰富字典。

The os module starts by importing all names from a platform-specific submodule (such as _nt or _posix) then does a little normalization. Clearly the environ name (standing for the system environment) was defined by the platform-specific submodule (as it's normally expected to be!!!), so the except clause in os.py didn't trigger and os.environ is just the rich dictionary it's normally supposed to be.

萌无敌 2024-08-23 19:29:00

os.py 中引用的代码是一个备份。它的意思是,如果没有人定义一个 environ 变量,请创建一个,并使用一个空字典作为值。

environ 确实存在,因为它已由第 58 行进一步导入:

from nt import *

如果您运行的是 Windows,以及其他平台的类似特定于平台的导入。因此,在实践中,environ 将始终存在,并且空字典后备将永远不会被使用。

那为什么还要提供后盾呢?好吧,它在现实世界中的用处值得怀疑,因为据我所知,核心 Python 发行版当前支持的所有平台都实现了正确的环境查找。然而,可能存在或曾经存在过,Python 运行的不寻常平台没有环境变量,并且在开发新平台时,当环境变量等系统接口没有设置时,避免大量程序无法运行可能会很有用。还没写。

The quoted code from os.py is a backstop. It's saying, if no-one has yet defined an environ variable, create one, with an empty dictionary as a value.

But environ does exist, because it has been imported by this further up on line 58:

from nt import *

if you're running Windows, and similar platform-specific imports for other platforms. So in practice environ will always exist and the empty dict backstop will never be used.

Why bother provide a backstop then? Well, it's of dubious usefulness in the real world since as far as I can see all the platforms currently supported by the core Python distribution do implement a proper environ lookup. However there may be, or have been, unusual platforms where Python runs that do not have environment variables, and it may be of use when developing a new platform not to have a lot of programs fail to run when system interfaces like environment variables are not written yet.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文