简体   繁体   中英

.env file always returning None using os.environ.get() and os.environ[]

I'm trying to access the.env file but it always returns None, here is my file structure:

在此处输入图像描述

In my.env file, I've written:

BOT_TOKEN=someHiddenText
CLIENT_ID=anotherHiddenText
CLIENT_SECRET=anotherHiddenText

I've tried doing:

print(os.environ.get('BOT_TOKEN'))
print(os.environ['BOT_TOKEN'])

And both of these methods return None, so what am I doing wrong here? Any reply will be appreciated. Here is also the error message just in case it's useful.

(environment) PS C:\Users\Steven Kristian\Documents\Portfolio\Tohru> heroku local worker
[OKAY] Loaded ENV .env File as KEY=VALUE Format
11:48:10 worker.1   |  None
11:48:10 worker.1   |  None
11:48:10 worker.1   |  Traceback (most recent call last):
11:48:10 worker.1   |    File "app.py", line 16, in <module>
11:48:10 worker.1   |      TOKEN = os.environ['BOT_TOKEN']
11:48:10 worker.1   |    File "C:\Users\Steven Kristian\AppData\Local\Programs\Python\Python38\lib\os.py", line 673, in __getitem__
11:48:10 worker.1   |      raise KeyError(key) from None
11:48:10 worker.1   |  KeyError: 'BOT_TOKEN'
[DONE] Killing all processes with signal  SIGINT
11:48:10 worker.1   Exited with exit code null

os.environ can only get variables that are defined on your host (like HOME, USER, etc) and not from a file. You either set/export them before you run your script:

BOT_TOKEN="asdfghjkl" python script.py

export BOT_TOKEN="asdfghjkl"; python script.py

or use a python library like python-dotenv to get env config for your project:

pip install python-dotenv

then you can load your.env vars by doing

from dotenv import dotenv_values

config = dotenv_values(".env")
print(config["BOT_TOKEN"])

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