Reputation: 431
I am trying to use python-dotenv, but the environment variables I'm trying to pass keep coming up as 'None'. I have two files in the folder: .env & settings.py
I have the following in my .env file:
TEST_VAR=jkh45k3j4h5k34j
And I have the following in the same folder in my settings.py:
import os
from dotenv import load_dotenv
load_dotenv()
test_var = os.getenv("TEST_VAR")
print(test_var)
The output I get when running python3 settings.py
is:
None
Why am I not able to get the variable passed through to settings.py?
Upvotes: 20
Views: 31176
Reputation: 11
i know this post is old but if anyone happens to be here and the dotenv still returns 'none'. try this:
example.ev
API_KEY=abcdeFGHIJ123456
main.py
from dotenv import load_dotenv
import os
load_dotenv('example.env')
print(os.getenv('API_KEY')
output:
abcdeFGHIJ123456
this should work.
Upvotes: 1
Reputation: 369
I had the same problem. After quick testing in my code, I noted that
from dotenv import load_dotenv
load_dotenv(".env")
doesn't load .env file properly (that's why it returns None to environment variables). The file is in the same directory.
When used find_dotenv instead of file path/name it works well.
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
For info, find_dotenv is a function that automatically finds .env file.
Upvotes: 9
Reputation: 672
load_dotenv()
should also work without the specified path, as stated here: "load_dotenv
will load environment variables from a file named .env in the current directory or any of its parents or from the path specificied." Anyway, it wasn't working for me or OP.
In my case, specifying the path in the code wasn't a viable option, but I needed to automatically find the .env-file. Long story short, this does the job:
load_dotenv(find_dotenv())
Upvotes: 4
Reputation: 11
import os
from dotenv import load_dotenv
### give the full path
path='/user/.../.env'
load_dotenv(dotenv_path=path,verbose=True)
test_var = os.getenv("TEST_VAR")
print(test_var)
Upvotes: 0
Reputation: 239
You have to give the full path to load_dotenv
import os
from dotenv import load_dotenv
# Get the path to the directory this file is in
BASEDIR = os.path.abspath(os.path.dirname(__file__))
# Connect the path with your '.env' file name
load_dotenv(os.path.join(BASEDIR, '.env'))
test_var = os.getenv("TEST_VAR")
print(test_var)
Upvotes: 22