AppDividend
Latest Code Tutorials

How To Set Environment Variables In Python

0

In this tutorial, we will see How To Set Environment Variables In Python. To set and get environment variables in Python is the same as working with dictionaries. You need to import the os module. We can set the environment variable in Python using the os module. Let’s deep dive into how to setup env variables.

Why use Environment Variables in Python

Environment variables are very useful when you want to avoid hard-coding access credentials or other variables into code.

For instance, you may need to pass your API credentials for an email service provider to send email notifications, but you don’t want these credentials stored in your code repository. Due to environment variables, we can securely commit the files in Github repo.

Sometimes you need your code to function slightly differently between your development, staging, and production environments.

In this case, you could pass in the environment variable to tell your application what environment it’s running in.

These are the typical use cases for environment variables.

Most cloud service providers will have the CLI or web interface that lets you to configure the environment variables for your development, staging or production environments.

How To Set Environment Variables In Python

Python os module environ works as the dictionary that holds the environment variables available to the program at that moment.

The environment variables gets generated when the os module is loaded, so any further change in the env variables through other ways, such as export via Terminal, will not be reflected so, please keep in mind that.

See the following example.

# app.py

import os

# Set environment variables
os.environ['API_USER'] = 'SuperUser'
os.environ['API_PASSWORD'] = 'CIAArea51'

# Get environment variables
USER = os.getenv('API_USER')
PASSWORD = os.environ.get('API_PASSWORD')

# Getting non-existent keys
FOO = os.getenv('FOO') # None
BAR = os.environ.get('BAR') # None
MILLIE = os.environ['BROWN']

If you run the above code, then you will get the following output.

➜  pyt python3 app.py
Traceback (most recent call last):
  File "app.py", line 13, in <module>
    MILLIE = os.environ['BROWN']
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/os.py", line 669, in __getitem__
    raise KeyError(key) from None
KeyError: 'BROWN'
➜  pyt

One thing to note that using getenv() or the get() method on a dictionary key will return None if the key does not exist.

However, in the example with BAZ, if you reference a key in a dictionary that does not exist, it will raise a KeyError.

Print Current Environment Variables

If we want to print the current environment variables, then we can use the os.environ function.

See the following code.

# app.py

import os

# current environment variables
print(os.environ)

Output

➜  pyt python3 app.py
environ({'TERM_SESSION_ID': 'w0t0p0:372BDC94-31F4-40DE-82AB-E5D4AF313EAA', 'SSH_AUTH_SOCK': '/private/tmp/com.apple.launchd.e5m3lUABYb/Listeners', 'LC_TERMINAL_VERSION': '3.3.7', 'COLORFGBG': '15;0', 'ITERM_PROFILE': 'Default', 'XPC_FLAGS': '0x0', 'PWD': '/Users/krunal/Desktop/code/pyt', 'SHELL': '/bin/zsh', 'LC_CTYPE': 'UTF-8', 'TERM_PROGRAM_VERSION': '3.3.7', 'TERM_PROGRAM': 'iTerm.app', 'PATH': '/Users/krunal/Desktop/code/flutter/bin:/Users/krunal/.yarn/bin:/Users/krunal/.config/yarn/global/node_modules/.bin:/usr/local/opt/php@7.2/bin:/Users/krunal/.composer/vendor/bin:/Users/krunal/.cargo/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/go/bin:/usr/local/share/dotnet:~/.dotnet/tools:/Library/Frameworks/Mono.framework/Versions/Current/Commands:/Applications/Xamarin Workbooks.app/Contents/SharedSupport/path-bin', 'LC_TERMINAL': 'iTerm2', 'COLORTERM': 'truecolor', 'TERM': 'xterm-256color', 'HOME': '/Users/krunal', 'TMPDIR': '/var/folders/7m/122nrwsx5451db3nvfh157zh0000gn/T/', 'USER': 'krunal', 'XPC_SERVICE_NAME': '0', 'LOGNAME': 'krunal', 'ITERM_SESSION_ID': 'w0t0p0:372BDC94-31F4-40DE-82AB-E5D4AF313EAA', '__CF_USER_TEXT_ENCODING': '0x1F5:0x0:0x0', 'SHLVL': '1', 'OLDPWD': '/Users/krunal/Desktop/code', 'ZSH': '/Users/krunal/.oh-my-zsh', 'JAVA_HOME': '/Library/Java/Home', 'PAGER': 'less', 'LESS': '-R', 'LSCOLORS': 'Gxfxcxdxbxegedabagacad', '_': '/Library/Frameworks/Python.framework/Versions/3.6/bin/python3', '__PYVENV_LAUNCHER__': '/Library/Frameworks/Python.framework/Versions/3.6/bin/python3'})
➜  pyt

It will print all the current environment variables existing in Python.

How to check if the environment variable exists or not

We can use the if statement to check the environment variables exist or not.

# app.py

import os

if 'TERM_SESSION_ID' in os.environ:
    print('TERM_SESSION_ID environment variable is already defined. Value =', os.environ['TERM_SESSION_ID'])
else:
    print('TERM_SESSION_ID environment variable is not defined.')

Output

➜  pyt python3 app.py
TERM_SESSION_ID environment variable is already defined. Value = w0t0p0:372BDC94-31F4-40DE-82AB-E5D4AF313EAA
➜  pyt

In the above code, we can see that TERM_SESSION_ID is defined, and we have printed its value in the console.

We can not just change any default environment variable because changing the environment variable value can have serious implications for the execution of the program.

Hence, it’s advisable first to check if the environment variable exists or not. Then it’s up to you whether you want to modify the value or not. You can always define a new environment variable and use it in your program, which is the best practice.

Set Environment Variables in Python

Setting an environment variable is just like we set the values in the Python dictionary.

# app.py

import os

os.environ['NODE_VERSION'] = '13.2.0'
print('Lastes Node Version =', os.environ['NODE_VERSION'])

Output

➜  pyt python3 app.py
Lastes Node Version = 13.2.0
➜  pyt

It is like setting the dictionary values.

This is the one way to print the Environment variables. We will see another in the next subtopic.

An environment variable key-value pair must be a string; otherwise, an error will be raised. 

Get Environment Variables in Python

We can use the get() function of the environ variable.

If the environment variable is not present, then it will return None.

See the code.

# app.py

import os

os.environ['NODE_VERSION'] = '13.2.0'
print(os.environ.get('NODE_VERSION'))

Output

➜  pyt python3 app.py
13.2.0
➜  pyt

Let’s say if we try to get the PHP version, which is not defined, and then we get None in the output.

# app.py

import os

print(os.environ.get('PHP_VERSION'))

Output

➜  pyt python3 app.py
None
➜  pyt

Conclusion

In every programming language, there is a concept of Environment Variables, which provides us a secure way to defined secret variables like credentials.

Finally, How To Set Environment Variables In Python Example Tutorial is over.

Recommended Posts

Python print() function

Python dir() function

Python exec() function

Python open() function

Python next() function

Leave A Reply

Your email address will not be published.

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