Python Get Environment Variable with Example

In this chapter, we will learn how Python gets environment variables, certainly with examples. Apart from that, you’ll discover how to store local “env” variables in Python.

What are Environment Variables?

Environment variables are dynamic, named values that can affect the behavior of running processes.

They are part of the environment in which a process runs, providing configuration settings and other information that programs may require to function correctly.

How to set and get environment variables in python?

We can use the “os method” to set and get environment variables in Python application.

For Example:

import os

# Set environment variables
os.environ['SOURCE_USER'] = 'itsourcecode'
os.environ['SOURCE_PASSWORD'] = 'pies123'

# Get environment variables
USERNAME = os.getenv('SOURCE_USER')
U_PASSWORD = os.environ.get('SOURCE_PASSWORD')

# Getting non-existent keys
JASON = os.getenv('JASON') 
RUEL = os.environ.get('RUEL') 
DIEGO = os.environ['DIEGO'] 

Reminders: To use the getenv() or get() method, When the key does not exist the dictionary key will not return “none“.

Meanwhile, for the example program above with the variable name “DIEGO“. If the reference key in so called dictionary doesn’t exist it will raise a "keyerror“.

Environment variables help avoid hard-coding access credentials or other variables. To send email notifications, you may require API credentials for an email service provider, but you wouldn’t want to store them in your code repository.

Or maybe you require different codes for development, staging, and production. You could send an environment variable to your app to tell it where it’s executing. Environment variables have several uses.

Also read: Python Min Function Simple Implementation

How to storing local “env” variables?

Time needed: 5 minutes

Try to create a Python script to access environment variables in any scenario. This could be your local virtual environment or hosting service. How to utilize Python Decouple to simplify this operation.

  1. Install Python Decouple

    The first step is to install the Python Decouple in your local Python environment.
    $ pip install python-decouple

  2. Create “.env”

    The second step is after installing the Python decouple. We will create a “.env” in the root of our project folder. Then you can add your environment variables.
    $ touch .env # create a new .env file
    $ nano .env # open the .env file in the nano text editor

  3. Add environment variables

    The third step is after creating the “.env“, We will need the environment variables like this below.
    USER=alex
    KEY=hfy92kadHgkk29fahjsu3j922v9sjwaucahf

  4. Save the file

    Finally, the fourth step is we’ll save the file and exit the nano editor. The environment variables will be stored right away in your “.env file“.

  5. Access in Python Code

    Last but not least, if you already have environment variables stored in your “.env file“. Try to access them in python code similar below:
    from decouple import config
    API_USERNAME = config(‘USER’)
    API_KEY = config(‘KEY’)

How to get environment variables in Python?

To get the environment variable in python by modifying computer settings. Python programs’ output depends on environment variables. When environment variables change, the python script must be modified to produce the desired output.

This can be fixed by reading and setting the Python script’s environment variable. It eliminates manually modifying the environment variable and makes the code safer by hiding sensitive data like the API token.

How do I find my Python environment variable path?

To find my Python “env” variable path by using a method to extract the value variable key if it exists called getenv() method. Whereas it will return the default value.

Reminders: A module that  python provides an interface to interact in the operating system is called OS MODULE

Conclusion

To conclude that to get the environment variable python the programs’ output depends on environment variables. Environment variables help avoid hard-coding access credentials or other variables.

You could send an environment variable to your app to tell it where it’s executing. It eliminates manually modifying the environment variable and makes the code safer by hiding sensitive data like the API token.

When you release your program to a cloud service, you can set specific env. variables using whatever methods or syntax the provider has, and Python code should still be able to access them. It’s standard to capitalize global constants in programming.

Leave a Comment