Is there any difference at all between these two? When should I use one over the other? Is one of these deprecated? They seem to have the exact same functionality.
这两者之间有什么不同吗?我何时应该使用另一个?其中一个被弃用了吗?它们似乎具有完全相同的功能。
>>> os.getenv('TERM')
'xterm'
>>> os.environ.get('TERM')
'xterm'
>>> os.getenv('FOOBAR', "not found") == "not found"
True
>>> os.environ.get('FOOBAR', "not found") == "not found"
True
3 个解决方案
#1
34
One difference observed (Python27):
观察到一个差异(Python27):
os.environ
raises an exception if the environmental variable does not exist. os.getenv
does not raise an exception, but returns None
如果环境变量不存在,os.environ会引发异常。 os.getenv不会引发异常,但会返回None
#2
38
See this related thread. Basically, os.environ
is found on import, and os.getenv
is a wrapper to os.environ.get
, at least in CPython.
请参阅此相关主题。基本上,os.environ是在导入时找到的,而os.getenv是os.environ.get的包装器,至少在CPython中是这样。
EDIT: To respond to a comment, in CPython, os.getenv
is basically a shortcut to os.environ.get
; since os.environ
is loaded at import of os
, and only then, the same holds for os.getenv
.
编辑:为了回应评论,在CPython中,os.getenv基本上是os.environ.get的快捷方式;因为os.environ是在导入os时加载的,只有这样,os.getenv也是如此。
#3
13
In Python 2.7 with iPython:
在使用iPython的Python 2.7中:
>>> import os
>>> os.getenv??
Signature: os.getenv(key, default=None)
Source:
def getenv(key, default=None):
"""Get an environment variable, return None if it doesn't exist.
The optional second argument can specify an alternate default."""
return environ.get(key, default)
File: ~/venv/lib/python2.7/os.py
Type: function
So we can conclude os.getenv
is just a simple wrapper around os.environ.get
.
所以我们可以得出结论os.getenv只是os.environ.get的简单包装器。
#1
34
One difference observed (Python27):
观察到一个差异(Python27):
os.environ
raises an exception if the environmental variable does not exist. os.getenv
does not raise an exception, but returns None
如果环境变量不存在,os.environ会引发异常。 os.getenv不会引发异常,但会返回None
#2
38
See this related thread. Basically, os.environ
is found on import, and os.getenv
is a wrapper to os.environ.get
, at least in CPython.
请参阅此相关主题。基本上,os.environ是在导入时找到的,而os.getenv是os.environ.get的包装器,至少在CPython中是这样。
EDIT: To respond to a comment, in CPython, os.getenv
is basically a shortcut to os.environ.get
; since os.environ
is loaded at import of os
, and only then, the same holds for os.getenv
.
编辑:为了回应评论,在CPython中,os.getenv基本上是os.environ.get的快捷方式;因为os.environ是在导入os时加载的,只有这样,os.getenv也是如此。
#3
13
In Python 2.7 with iPython:
在使用iPython的Python 2.7中:
>>> import os
>>> os.getenv??
Signature: os.getenv(key, default=None)
Source:
def getenv(key, default=None):
"""Get an environment variable, return None if it doesn't exist.
The optional second argument can specify an alternate default."""
return environ.get(key, default)
File: ~/venv/lib/python2.7/os.py
Type: function
So we can conclude os.getenv
is just a simple wrapper around os.environ.get
.
所以我们可以得出结论os.getenv只是os.environ.get的简单包装器。