os.environ 在哪里初始化?
使用此代码,会输出许多键,但我期望没有输出:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
os
模块首先从特定于平台的子模块(例如_nt
或_posix
)导入所有名称,然后进行一些标准化。显然,environ
名称(代表系统环境)是由特定于平台的子模块定义的(正如通常预期的那样!!!),因此
子句没有触发,而os.py
中的 exceptos.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 theenviron
name (standing for the system environment) was defined by the platform-specific submodule (as it's normally expected to be!!!), so theexcept
clause inos.py
didn't trigger andos.environ
is just the rich dictionary it's normally supposed to be.os.py 中引用的代码是一个备份。它的意思是,如果没有人定义一个
environ
变量,请创建一个,并使用一个空字典作为值。但
environ
确实存在,因为它已由第 58 行进一步导入:如果您运行的是 Windows,以及其他平台的类似特定于平台的导入。因此,在实践中,
environ
将始终存在,并且空字典后备将永远不会被使用。那为什么还要提供后盾呢?好吧,它在现实世界中的用处值得怀疑,因为据我所知,核心 Python 发行版当前支持的所有平台都实现了正确的环境查找。然而,可能存在或曾经存在过,Python 运行的不寻常平台没有环境变量,并且在开发新平台时,当环境变量等系统接口没有设置时,避免大量程序无法运行可能会很有用。还没写。
The quoted code from
os.py
is a backstop. It's saying, if no-one has yet defined anenviron
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: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.