Is there any difference at all between both approaches?
>>> 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
They seem to have the exact same functionality.
While there is no functional difference between
os.environ.get
andos.getenv
, there is a massive difference betweenos.putenv
and setting entries onos.environ
.os.putenv
is broken, so you should default toos.environ.get
simply to avoid the wayos.getenv
encourages you to useos.putenv
for symmetry.os.putenv
changes the actual OS-level environment variables, but in a way that doesn't show up throughos.getenv
,os.environ
, or any other stdlib way of inspecting environment variables:You'd probably have to make a ctypes call to the C-level
getenv
to see the real environment variables after callingos.putenv
. (Launching a shell subprocess and asking it for its environment variables might work too, if you're very careful about escaping and--norc
/--noprofile
/anything else you need to do to avoid startup configuration, but it seems a lot harder to get right.)See this related thread. Basically,
os.environ
is found on import, andos.getenv
is a wrapper toos.environ.get
, at least in CPython.EDIT: To respond to a comment, in CPython,
os.getenv
is basically a shortcut toos.environ.get
; sinceos.environ
is loaded at import ofos
, and only then, the same holds foros.getenv
.One difference observed (Python27):
os.environ
raises an exception if the environmental variable does not exist.os.getenv
does not raise an exception, but returns NoneIn Python 2.7 with iPython:
So we can conclude
os.getenv
is just a simple wrapper aroundos.environ.get
.In addition to the answers above: