Reputation: 3092
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!
Upvotes: 14
Views: 8637
Reputation: 838796
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/:
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
Upvotes: 14
Reputation: 17036
I'm struggling to understand how standardizing on one or another would not introduce serious violations of the principle of least astonishment.
On windows, programmers are used to case insensitivity... why would a windows-only programmer expect to have to picky about this? Note that there is no possible way to implement case-sensitive environment variables here, that option simply doesn't work.
In the linux world, ENVVAR and envvar are two different variables, you cannot standardize to the windows mechanism without potentially hiding information.
In the version that is implemented, you force the developer to specify upper or lower case for a cross-platform app. The case specification is irrelevant on windows, and you'd have to do it anyways for *nix.
Upvotes: 1
Reputation:
Platform independence often means getting worse of all platforms. So for a platform-independent manner you have assume that environment variables are case-sensitive but never try to rely on this (i.e. not create variables with same names in different case intentionally) but be able to handle it. Otherwise you may screw up on non-Windows.
As for what platforms are case-sensitive and what are not - simply. Windows is not case-sensitive, and Unix-like OSs are case sensitive, see:
For exotic operating systems you have to check its documentation.
Hope it helps.
Upvotes: 1