DEV Community

Discussion on: Using .env Files for Environment Variables in Python Applications

Collapse
 
bastarrd profile image
Basstardd

Tnx for article! But there is one important caveat here: if you use Linux for example you can not use env names like HOME or NAME or LOGNAME. Because your app variables from .env file (in currently working directory) will be overwritten by the global (from Linux).

For example: in case you put in .env NAME=Michale and you are logged in as user Daniel, inside your python script os.getenv("NAME") will return Daniel instead of Michael. And most probably this is not something you want in your app....

I guess there is different ways to resolve this, but most obvious one for me is to avoid this names entirely and to use some convention like APP_NAME or APP_HOME_DIR....

Collapse
 
prborg profile image
Jose Cintron • Edited

You can actually use HOME or whatever variable you want, but you cannot use load_dotenv to read the .env file. Instead of load_dotenv you have to use dotenv_values("YOUR_FILE_HERE")["VARIABLE_HERE"]. So something like this will work

.env
   HOME=foobar

python
   from dotenv import dotenv_values

   # Load shodan API key
   HOME = dotenv_values(".env")["HOME"]

   print(HOME)
Enter fullscreen mode Exit fullscreen mode