Difference between os.getenv and os.environ.get
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.
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 foros.getenv
.
One difference (observed in Python 2.7 and 3.8) between getenv()
and environ[]
:
os.getenv()
does not raise an exception, but returns Noneos.environ.get()
similarly returns Noneos.environ[]
raises an exception if the environmental variable does not exist
In Python 2.7 with iPython:
>>> 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.pyType: function
So we can conclude os.getenv
is just a simple wrapper around os.environ.get
.