-->
How to Export/Set and Import/Retrieve Environment Variables Python

How to Export/Set and Import/Retrieve Environment Variables Python

Back to top

Updated by Ashirafu Kibalama on September 17, 2024

"How to Export and Import Environment Variables in Python"






Environment variables are crucial for configuring applications and scripts without altering the codebase.


They store key-value pairs for settings, secrets, and other vital data. Managing these variables is essential for developing robust, adaptable, and secure Python applications.


This guide explores how to handle environment variables in Python using the OS module and the python-dotenv package.


It covers single script setups, configuration management across multiple environments, and secure handling of sensitive data.


The os module can export and import environment variables in Python. Here's a step-by-step guide for both exporting and importing environment variables:


Watch my YouTube video on How to Export/Set and Import/Retrieve Environment Variables Python.






Exporting or Setting Environment Variables

You can set (export) environment variables in Python using the os.environ[]. Here's an example:


import os

# Set environment variables
os.environ['MY_VARIABLE'] = 'myvaluedf45fvbsgfhs344afgs3445'
os.environ['ANOTHER_VARIABLE'] = 'anothervalue523673723fgstydsvcgf'

print('\n--------- Verify the variables are set or Exported using os.environ[] ---------\n')
# Verify the variables are set
print(f"my_variable = {os.environ['MY_VARIABLE']}\n") # Output: my_value
print(f"another_variable = {os.environ['ANOTHER_VARIABLE']}") # Output: another_value



Output:








Importing or Retrieving Environment Variables

To retrieve (import) environment variables, you can also use the os.environ.get(). Here's an example:


import os


# Set environment variables
os.environ['MY_VARIABLE'] = 'myvaluedf45fvbsgfhs344afgs3445'
os.environ['ANOTHER_VARIABLE'] = 'anothervalue523673723fgstydsvcgf'

# print('\n--------- Verify the variables are set or Exported using os.environ[] ---------\n')
# # Verify the variables are set
# print(f"my_variable = {os.environ['MY_VARIABLE']}\n") # Output: my_value
# print(f"another_variable = {os.environ['ANOTHER_VARIABLE']}") # Output: another_value


print('\n--------- Retrieve or Import environment variables using os.environ.get() ---------\n')

# Retrieve environment variables
my_variable = os.environ.get('MY_VARIABLE')
another_variable = os.environ.get('ANOTHER_VARIABLE')

print(f'my retrieved data: {my_variable}\n') # Output: my_value
print(f'another retrieved data: {another_variable}') # Output: another_value


Output:



complete code:

import os


# Set environment variables
os.environ['MY_VARIABLE'] = 'myvaluedf45fvbsgfhs344afgs3445'
os.environ['ANOTHER_VARIABLE'] = 'anothervalue523673723fgstydsvcgf'

print('\n--------- Verify the variables are set or Exported using os.environ[] ---------\n')
# Verify the variables are set
print(f"my_variable = {os.environ['MY_VARIABLE']}\n") # Output: my_value
print(f"another_variable = {os.environ['ANOTHER_VARIABLE']}") # Output: another_value


print('\n--------- Retrieve or Import environment variables using os.environ.get() ---------\n')

# Retrieve environment variables
my_variable = os.environ.get('MY_VARIABLE')
another_variable = os.environ.get('ANOTHER_VARIABLE')

print(f'my retrieved data: {my_variable}\n') # Output: my_value
print(f'another retrieved data: {another_variable}') # Output: another_value



Complete Output:







Exporting and Importing Environment Variables from a .env File

Sometimes, you can store environment variables in a file and load them into your script. This is common in configuration files like .env. You can use the dotenv package to facilitate this.


Install the python-dotenv package:



pip install python - dotenv






Create a .env file with your environment variables:







Add your secret info. Example:




Load the .env file in your Python script:


import os
from dotenv import load_dotenv

# loading your .env info to this script
load_dotenv('.env')

password: str = os.getenv('PASSWORD')
print(password)
username: str = os.getenv('USER')
print(username)

api_key: str = os.getenv('API_KEY')

print(api_key)

url = f'www.testcodeenv.com?format/api={api_key}?user={username}?password={password}'

print(url)


OutPut:







This approach is beneficial for managing environment variables in different environments (development, testing, production).


Summary

  • Exporting: Use os.environ to set environment variables.
  • Importing: Use os.environ.get or os.getenv to retrieve environment variables.
  • From a file: Use the python-dotenv package to load environment variables from a .env file.


Conclusion

Understanding how to manage environment variables is essential for developing Python applications.


Learning to export and set environment variables using the OS module and tools like the python-dotenv package can ensure your application's configuration is robust and adaptable.


Keep these best practices in mind as you develop and deploy Python applications.


Related Posts:

1 What is Environment Variable, and Why Use Environment Variables in Python?


2 2 Methods To Set Python Environment Variable Windows 10 (with a step-by-step YouTube Video Guide)


Other Posts:

Best 4 Free Exchange Rate APIs With Python Examples (Step-by-Step with YouTube Video)


Build a CV or Resume Generator pdf Flask Python With Source Code (Step-by-Step with YouTube Video) 


3 Ckeditor Alternative: How To Upload An Image Ckeditor Flask Alternative/ Summernote Image Upload Flask Python


A Beginner's Complete Guide: Deploy Flask App with SQLite/ PostgreSQL Database on cPanel/ shared hosting 


5 How to fix: Python was not found Error: Run without arguments to install from the Microsoft Store or disable this shortcut from Settings Manage App Execution Aliases.


6 How to Change or Activate a Virtual Environment in Pycharm Windows/ macOS