- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Access environment variable values in Python
Environment variables in Python are configuration values stored outside the code and are used at runtime by the application. These variables are present in the form of key-value pairs just like dictionaries in Python. These variables can be set, updated, or removed from the configuration file without changing the application code. Python gives many operating systems functions to access environment variables without affecting the code of the application. In this article, we will learn the ways in which we can access environment variables in Python.
Using the OS Module
In order to interact with the operating system python has an os module with help of which you can interact with the os as well as access the environment variable. The os.environ dictionary contains all the environment variables in key-value pairs.
We can use the os.environ to access the Path of the environment variable and also any new environment variable value.
Example
import os # get the value of the PATH environment variable path = os.environ['PATH'] print(path) # set a new environment variable os.environ['MY_VAR'] = 'my value' # get the value of the new environment variable my_var = os.environ['MY_VAR'] print(my_var)
Output
/opt/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/tools/node/bin:/tools/google-cloud-sdk/bin my value
Example
If the environment variable is not found then a key Error is raised by the code. To avoid such errors we can use os.environ.get() function to access environment variables and avoid key Errors if the key is not found.
import os # get the value of the MY_VAR environment variable, or return None my_var = os.environ.get('MY_VAR') print(my_var)
Output
None
Using the Dotenv Module
In the industry, we use different environments while working on development, staging, and production codebase. Each of these environments has separate environment variable files. Dotenv is a third-party library that is used to access environment variables in multiple environments.
Installation
To use dotenv module we have first to install python-dotenv by the following command
pip install python-dotenv
Pip is the python package manager. Pip install python-dotenv installs the dotenv module into your local file system.
After installing the python-dotenv module we have to create a .env file in the root directory of our project and create environment values in it as key-value pairs.
MY_KEY_VAR=my_value
The My_KEY_VAR is the key of the env variable and my_value is the value corresponding to it.
Now, we can load the .env file in our Python code wherever required using the dotenv.load_dotenv() function which reads the .env file and loads all environment variables in the os.environ module.
Example
from dotenv import load_dotenv import os # load the environment variables from the .env file load_dotenv() # get the value of the MY_VAR environment variable my_var = os.environ['MY_KEY_VAR'] print(my_var)
Output
my_value
Using the Argparse Module
The argparse is a standard library in python that is used to parse command-line arguments. We can pass environment variables as command-line arguments in Python using the argparse library.
Algorithm
Define a command line argument for each environment variable we want to pass.
Then access the environment variable using the args object returned by argparse.
Pass the environment variable with its value when running the file.
Example
import argparse parser = argparse.ArgumentParser() parser.add_argument('--my-var') args = parser.parse_args() my_var = args.my_var print(my_var)
Output
None
When running the above file we need to pass the env value with the key name.
python script.py --my-var "my value"
When we pass the –my-var option with its value “my value” in the command line, the parse_ags() of the argparse module parses the option and picks up the value of the option i.e “my_value”.
Using the Config Parser Module
The Config parser is a python library which is used to read configuration files in python applications.
Algorithm
To use config parser module we have to
Create a configuration file and declare environment variables in the form of key value pairs for each section like development, production and staging if required.
Access the current environment using the os.getenv() function in the python file.
In the python file where we need to access environment variables we can use the ConfigParser module to access the environment variables of the current environment.
[development] MY_VAR=my value [production] MY_VAR=another value import configparser import os # get the current environment env = os.getenv('ENVIRONMENT', 'development') # read the configuration file config = configparser.ConfigParser() config.read('config.ini') # get the value of the MY_VAR environment variable for the current environment my_var = config.get(env, 'MY_VAR') print(my_var)
Conclusion
In this article, we explored different ways in which we can access the environment variables in the Python file. We understood how to use the os module to access the environment variable, how to use the dotenv library to access environment variables in multiple environments, how to use the argparse module to pass the environment variables as a command line argument, and also how to use ConfigParser module to access the environment variable of the current environment from multiple environments.