Python environment case senstivity - os.environ [...]

I need to access the process environment block in a platform independent way.

The python os module docs doesn't say anything about the case sensitivity of os.environ / os.getenv . Experimenting with my ubuntu and win7 dev box, I see that os.environ is case sensitive in linux, but not in windows (this reflects the set behavior on both platforms)

Since dict is obviously a case-senstive for string keys, it seems that the value returned by os.environ is only os.environ like dict ...

Question: Where / How can I find the final answer to this behavior? I'd rather get a real answer than just empirically define it :)

Alternatively, is os.getenv (...) better to use api? why?

Thanks!

+4
source share
3 answers

When the documentation does not indicate the behavior and you want to find 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/ :

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 the difference in implementations - key.upper() used instead of key in Windows:

Linux:

 def __setitem__(self, key, item): putenv(key, item) self.data[key] = item 

Window:

 def __setitem__(self, key, item): putenv(key, item) self.data[key.upper()] = item 
+9
source

Platform independence often means degradation of all platforms. Therefore, for a platform-independent method, you assume that the environment variables are case sensitive, but you never try to rely on it (i.e. do not intentionally create variables with the same name in different cases), but be able to process them. Otherwise, you may spoil non-Windows.

As for platforms, case-sensitive and what not. Windows is not case sensitive, and Unix-like operating systems are case sensitive:

For exotic operating systems, you should check its documentation.

Hope this helps.

+1
source

I am struggling to understand how the standardization of one or the other will not lead to serious violations of the principle of least surprise.

In windows, programmers are used to account for the insensitivity ... why can a programmer who depends only on windows count on this? Please note that it is not possible to implement case-sensitive environment variables here, this option simply does not work.

In the Linux world, ENVVAR and envvar are two different variables; you cannot standardize the Windows mechanism without potential hidden information.

In the version that is implemented, you force the developer to specify upper or lower case for the cross-platform application. The case specification is not related to windows, and you should do it anyway for * nix.

+1
source

All Articles