Search code examples
pythonpython-3.xsyntaxenvironment-variablesdotenv

How to load API keys from .env file successfully


I have been referring to tutorials on the web, but something keeps on going wrong even though I follow them exactly.

I am trying to hide some API keys inside .env file, this is the content of my .env(same directory as init.py):

CONNSTRING = DefaultEndpointsProtocol=samplesamplesameplsamplesample

and this is inside my init.py

from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
print(os.getenv("CONNSTRING"))

which does not work? not sure about the error, this is what it says:

System.Private.CoreLib: Result: Failure  
Exception: ModuleNotFoundError: No module named '__main__'

if usecwd or _is_interactive() or getattr(sys, 'frozen', False):
  File "D:\\\", line 265, in _is_interactive
    main = __import__('__main__', None, None, fromlist=['__file__'])

Solution

  • By default the .env should be at the same level as the file you execute. But you can specify a path as parameter of the load_dotenv method. Maybe you should try to get rid of the find_dotenv method and directly give the absolute path of your .env like so:

    import os                                                                                                                                                                                                          
    from dotenv import load_dotenv, find_dotenv
    from pathlib import Path
    load_dotenv(Path("/my/path/.env"))
    print(os.getenv("CONNSTRING"))