I need to access the process' environment block in a platform-independent manner.
The python os module docs don't specify anything about case-sensitivity of the os.environ
/ os.getenv
. Experimenting on my ubuntu and win7 dev box's, I see that os.environ is case sensitive on linux but not on windows (This mirrors the behavior of set
on both platforms)
Since dict's are obviously case-senstive for string keys, it appears that the value returned by os.environ
is only duck-typed as a dict...
Question: Where/How should I be able to find the definitive answer on this behavior? I would rather have a real answer than just empirically determine it :)
Alternatively, is os.getenv(...) a better api to use? why?
Thanks!
On Unix-like operating systems, environment variable names are case sensitive, but they are not on DOS, OS/2, and Windows.
The env variables come in as regular b2 variables which are case-sensitive. And making all of those upper-case would cause widespread breakage for b2 users. I'll have to see if there's some other work around in b2 for specific cases. I personally think this is a Python bug.
To set and get environment variables in Python you can just use the os module: import os # Set environment variables os. environ['API_USER'] = 'username' os. environ['API_PASSWORD'] = 'secret' # Get environment variables USER = os.
environ in Python is a mapping object that represents the user's environmental variables. It returns a dictionary having user's environmental variable as key and their values as value.
When the documentation doesn't specify the behaviour and you want to discover the answer yourself, you can look in the source code. In this case you can get the source code for os.py
online at http://svn.python.org/:
os.py
(Python trunk).os.py
(Python 2.7).The comments in the code say:
elif name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE
# But we store them as upper case
# ...
else: # Where Env Var Names Can Be Mixed Case
# ...
You can also see a difference in the implementations - key.upper()
is used instead of key
on Windows:
Linux:
def __setitem__(self, key, item):
putenv(key, item)
self.data[key] = item
Windows:
def __setitem__(self, key, item):
putenv(key, item)
self.data[key.upper()] = item
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With