'load_dotenv fails when running from a package

Using load_dotenv to read python variables from a .env file. Building a python package using the setup module and packaging it into a command get_values

Cases when code runs successfully

1- Codebase runs and I can read the environment values only if the command 'get_values' is running from the same directory as codebase.

2- Codebase runs as a standalone Python program

Cases, when code doesn't, runs successfully

1- After building the package, I run the commands 'get_values' the code fails to read the environment variables and get the string value as NoneType

Current Codebase hierarchy:

enter image description here .env file

OIDC_CLIENT_ID='xxxxxxxxxxx'

Code to read environment file

 basepath = Path()
 basedir = str(basepath.cwd())
 envars = basepath.cwd() / 'config.env'
 load_dotenv(envars)

Reading the environment variable

  print(os.getenv('OIDC_CLIENT_ID'))


Solution 1:[1]

Make sure your current working directory contains a 'config.env' file in the cases where it's not working.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sören