pythonherokuenvironment-variables

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

enter image description here

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

Solution

  • 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"])