Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would os.environ['foo'] not match os.getenv('foo')?

I have a small Python application, launched via subprocess.Popen, that takes some parameters in the form of environment variables. I do this by passing the environment structure into the Popen call. The program then reads the variables via os.getenv.

Or rather, it used to read them that way. On Windows, it worked fine. But on our FreeBSD servers, os.getenv returns None for all the parameters we passed in. The odd part is that os.environ has the values just fine—and, indeed, simply switching all os.getenv('foo') calls to os.environ['foo'] made everything work just fine on both platforms.

Why are these values different? When is one appropriate over the other?

like image 785
Benjamin Pollack Avatar asked Jun 08 '12 16:06

Benjamin Pollack


People also ask

What is difference between os environ and os Getenv?

getenv is basically a shortcut to os. environ. get ; since os. environ is loaded at import of os , and only then, the same holds for os.

What does os Getenv () do?

The os. getenv() method is used to extract the value of the environment variable key if it exists. Otherwise, the default value will be returned. Note: The os module in Python provides an interface to interact with the operating system.

How do I set an environ variable in 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

os.environ is created on import of the os module, and doesn't reflect changes to the environment that occur afterwards unless modified directly. Interestingly enough, however, os.getenv() doesn't actually get the most recent environment variables either, at least not in CPython. You see, in CPython, os.getenv() is apparently just a wrapper around os.environ.get() (see http://hg.python.org/cpython/file/6671c5039e15/Lib/os.py#l646). So it seems the main reason to use os.getenv() with the stated implementation is when you want to have a default value returned when an environment variable name isn't found in os.environ's keys rather than have a KeyError or whatever thrown, and you want to save a few characters.

It's entirely possible that the implementation on FreeBSD has some weird gimmick that causes it to act differently, but I'm not sure why that would be the case. Take a look at the copy of os.py on one of the FreeBSD machines you use, if you can.

like image 142
JAB Avatar answered Oct 09 '22 16:10

JAB