简体   繁体   中英

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

#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.

You need to call load_dotenv first.

#test.py
import os
from dotenv import load_dotenv

load_dotenv('var.env')

print(os.getenv('PROJECT'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM