#Python 🐍- Working with Environment Variables and python-dotnenv

Hi !

The Microsoft Cloud Advocates team is great and, hey everyday I learn something new. A couple of days ago we were talking about working with Environment Variables and Virtual Environments.

I wrote several times about working with Virtual Envs, like

And, I even solve this problem editing the activate and deactivate scripts a long time ago.

Today, I learn that we have the chance to use an amazing library to work with Environment Values: python-dotenv.

Note: for this specific scenario, we are going to define and load env values in a file named [.env].

Check the documentation of the package for a complete reference. Here are 3 steps to show how easy is to use.

We start installing the package

pip install python-dotenv

I created a new python file to test [demo.py] and in the same folder a file to store environment variables [.env].

file structure for venv load vars demo

A couple of code lines will get the values from the env file and … done !

import os
from dotenv import load_dotenv

print(f'Foo value from .env: {os.getenv("FOO")}')
print(f'Foo value from .env: {os.environ.get("FOO")}')

Super easy to use !

Happy coding!


El Bruno

More posts in my blog ElBruno.com.

More info in https://beacons.ai/elbruno


Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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

%d bloggers like this: