Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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!

like image 483
some bits flipped Avatar asked Oct 17 '11 17:10

some bits flipped


People also ask

Is os environ case-sensitive?

On Unix-like operating systems, environment variable names are case sensitive, but they are not on DOS, OS/2, and Windows.

Are environment variables case-sensitive in Python?

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.

How do I set environ variables in Python os?

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.

What does os environ do in Python?

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.


1 Answers

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
like image 195
Mark Byers Avatar answered Nov 21 '22 01:11

Mark Byers