Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use variables from an environment file Python?

I have a project that I’m working on in which I need to store sensitive information into an environment file as variables that can later be called in my code. I’m having issues with it working and so I’ve dumbed it down to the simplest test I can think of.

I have create a test.py file and a var.env file within the same directory. They are the only files in this directory.

Here is my test.py that simply tried to print the value

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#test.py
import os
from dotenv import load_dotenv

print(os.getenv('PROJECT'))

Here is environment file saved as var.env

#.env test file
PROJECT='newproject1234'

When I run test.py I get a response of "none". I know I’ve gotta be missing something simple here. Any help is appreciated.

>Solution :

You need to call load_dotenv first.

#test.py
import os
from dotenv import load_dotenv

load_dotenv('var.env')

print(os.getenv('PROJECT'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading