Python Friday #106: Accessing Environment Variables in Python

Environment variables are a useful way to store computer specific configuration values, like the home directory of the user or the temp folder. Let’s look how we can access the environment variables from our Python code.

This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.

 

Reading environment variables

We can read environment variables with the getenv() function of the os module:

The first argument is the name of the desired environment variable, while the second argument is an optional default value that is returned if the variable does not exist.

All environment variables are strings. If you expect a number you need to cast it:

 

Writing environment variables

There is no direct way to permanently change the environment variables in your Python code. To understand why this is the case, we need to look a little deeper at what happens behind the scenes of Python.

When your application starts, Python creates a copy of the environment variables and puts them into the os.environ dictionary. That is the place in which os.getenv() checks for the variables. You can modify that dictionary as you can change a value in any dictionary:

However, as soon as your application ends, the os.environ dictionary disappears and with it your changes. You can use the subprocess module and run the setx command on Windows to modify the environment variables of Windows:

This sets the variable on the operating system level, yet it will not be accessible in the console you run that command. This is because the console also works with a copy of the environment variable from the time you started the console itself, which was before you changed the variable.

Therefore, if you change an environment variable in one script and then want to access that variable in another script, you need to make sure that you restart the console between your scripts. This is cumbersome, but that is how environment variables work.

 

Next

As cumbersome as working with a copy of the environment variables can be, this behaviour can be of great help when working with sensitive configuration values. Next week we take a look at .env files and how they help with keeping your access keys a secret.

1 thought on “Python Friday #106: Accessing Environment Variables in Python”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.