Access Environment Variable Values in Python

Access Environment Variable Values in Python

The environment variables provide information about the environment of the system. In Python, accessing the environment allows us to interact with the system. You can access the environment variables in Python using the os.environ() method. In this blog, let’s explore how to access environment variables in Python and the multiple methods used with examples for each.

Table of Contents:

Methods to Access Environment Variables in Python

Python provides various built-in methods that can be used to access environment variables. Following are some of the commonly used methods explained with examples:

Method 1: Using os.environ() method to Access Environment Variables in Python 

Direct access to environment variables can be done with os.environ().

Example:

Python

Output:

Access Environment Variables in Python Output

Explanation: The print() displays all the environment variables present in the system environment.

Method 2: Using the os.environ Dictionary to Access Environment Variables in Python 

The os.environ shows dictionary-like behavior, you can get its values through the variable names as keys.

Example:

Python

Output:

Dictionary to Access Environment Variables in Python Output

Explanation: The os.environ dictionary gives access to environment variables. The print() returns the path of the environment variable.

Method 3: Using the os.getenv() method to Access Environment Variables in Python 

The os.getenv() becomes a more secure option to gain access to environment variables in Python. In case the variable is not present, you can assign a default value.

Example:

Python

Output:

Explanation: The os.getenv() function returns some variables from the environment. Nonexisting variables return some default value but do not give an error.

Method 4: Using dotenv package to Access Environment Variables in Python

The dotenv package helps in securely storing sensitive information in .env files.

Step 1: Installing  dotenv:

# Installing Python dotenv package using pip
pip install python-dotenv

Step 2: Creating .env File:

Create a .env file in the root directory of your project and add the following environment variables:

# Creating a Database_URL
DATABASE_URL=Intellipaatdatabaseurl
API_KEY=yourapikey

Example:

Python

Output:

Explanation: Here the environment variables are loaded from the .env file and are accessed using the os.getenv() which allows for access to sensitive data.

Method 5: Using the os.getlogin() method to Access Environment Variables in Python 

The os.getlogin() returns the username of the person who is logged in. Although it is not exactly an environment variable, it could be used to access user-defined environment variables.

Example:

Python

Output:

method to Access Environment Variables in Python Output

Explanation: Here, the name of the user who is presently logged into the system is returned. This allows accessing the user-based environment variables.

Alternate Ways to Use the Environment Variables

Using the Argparse Module to Pass the Environment Variables

The argparse Module lets you pass the environment variables as command-line arguments.

Example:

Python

Output:

Argparse Module to Pass the Environment Variables output

Explanation:  It imports the argparse module to work with command-line arguments. The parser object is created using ArgumentParser(). This variable is kept in my_var and printed.

Using the ConfigParser Module to Retrieve the Environment Variables

The ConfigParser module reads a configuration file and retrieves values based on a section.

Step 1: Create a config.ini File

Create the config.ini file and store environment variables.

# Adding two environment variables in the project folder

MY_VAR= intellipaat value

MY_VAR=another value

Step 2: Read Environment Variables from the Config File

Python

Output:

ConfigParser Module to Retrieve the Environment Variables output

Explanation: The ENVIRONMENT variable is fetched using os.getenv(). A ConfigParser object reads the config.ini file. The MY_VAR value for the current environment is retrieved and printed.

Conclusion

You can access environment variables using the os modules. os.environ[] gives you direct access, although if the variable does not exist, it raises an error. In comparison, os.getenv() is safer, as it provides a way to provide a default value. Choosing the right method allows proper and secure access to the environment variables.

FAQs

1. What are environment variables?

Environment variables store important settings and sensitive data like passwords or API keys.

2. How can I access an environment variable in Python?

Through os.environ[‘VAR_NAME’] or os.getenv(‘VAR_NAME’).

3. What happens if an environment variable does not exist?

The os.environ[‘VAR_NAME’] gives an error, but os.getenv(‘VAR_NAME’) returns None or a default value.

4. How do I load environment variables from a .env file?

You can use dotenv package with load_dotenv() to read values from a .env file.

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

Full Stack Developer Course Banner