问题描述
我有一个小的Python应用程序,通过 subprocess.Popen
启动,它以环境变量的形式获取一些参数。通过将环境结构传递到 Popen
调用中来执行此操作。程序然后通过 os.getenv
读取变量。
I have a small Python application, launched via subprocess.Popen
, that takes some parameters in the form of environment variables. I do this by passing the environment structure into the Popen
call. The program then reads the variables via os.getenv
.
或者说,它曾经以这种方式读取它们。在Windows上,它工作正常。但是在我们的FreeBSD服务器上,我们传递的所有参数 os.getenv
返回无
。奇怪的是 os.environ
的值很好,确实,只需切换所有 os.getenv('foo')
调用 os.environ ['foo']
使 平台上的一切都可以正常工作。
Or rather, it used to read them that way. On Windows, it worked fine. But on our FreeBSD servers, os.getenv
returns None
for all the parameters we passed in. The odd part is that os.environ
has the values just fine—and, indeed, simply switching all os.getenv('foo')
calls to os.environ['foo']
made everything work just fine on both platforms.
为什么这些值不同?
推荐答案
os.environ
是在导入 os
模块时创建,并且不会反映对之后发生的环境的更改,除非直接修改。然而,有趣的是, os.getenv()
实际上并没有获得最新的环境变量,至少不在CPython中。你看,在CPython中, os.getenv()
显然只是围绕 os.environ.get()
(请参阅)。因此,使用 os.getenv()
的主要原因是,当您想要在没有找到环境变量名称时返回默认值 os.environ
的密钥,而不是有$ code> KeyError 或任何抛出的东西,并且您要保存几个字符。
os.environ
is created on import of the os
module, and doesn't reflect changes to the environment that occur afterwards unless modified directly. Interestingly enough, however, os.getenv()
doesn't actually get the most recent environment variables either, at least not in CPython. You see, in CPython, os.getenv()
is apparently just a wrapper around os.environ.get()
(see http://hg.python.org/cpython/file/6671c5039e15/Lib/os.py#l646). So it seems the main reason to use os.getenv()
with the stated implementation is when you want to have a default value returned when an environment variable name isn't found in os.environ
's keys rather than have a KeyError
or whatever thrown, and you want to save a few characters.
完全可能的是,FreeBSD上的实现有一些奇怪的im头,导致它的行为不同,但我不知道为什么会这样。如果可以,请查看您使用的其中一个FreeBSD机器上的 os.py
的副本。
It's entirely possible that the implementation on FreeBSD has some weird gimmick that causes it to act differently, but I'm not sure why that would be the case. Take a look at the copy of os.py
on one of the FreeBSD machines you use, if you can.
这篇关于什么时候os.environ ['foo']不符合os.getenv('foo')?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!