'Pycharm Pro FastAPI default configuration not recognizing environment variables in files besides main.py

I have a FastAPI python app setup in Pycharm Pro with the default configurations. I've added environment variables to 'Run/Debug Configurations' window. I also have an .env file (which is gitignored) containing the same variables.

Apparently, this .env file is completely ignored by Pycharm when locally testing. Only the variables I've set inside the Run/Debug Configurations window are recognized - and these are only accessible from main.py, the file that runs the FastAPI app.

Accessing environment variables defined this way from main.py works with any of the following:

# these all work inside main.py but can't be accessed outside of main.py
os.environ['VAR_HERE']
os.environ.get['VAR_HERE']
os.getenv['VAR_HERE']

Why isn't Pycharm recognizing environment variables outside of main.py (in helper modules, etc.) ? How can I get Pycharm to recognize environment variables outside of main.py ?

I'm hosting this app on Heroku. I have an external redis init file which references a Heroku-stored config var with no issues. For some reason, redis is also working correctly locally too. But if I try running the redis init file from Pycharm directly, print statements show environment variables as "None"...

What am I not getting here?



Solution 1:[1]

For the .env file to be activated you have to set the working directory the the directory where the .env file is located. This is usually outside of the module root, where your app.py or main.py lives; if you don't do this, the working directory is set inside the module itself - and the .env file isn't picked up. This is the default behavior when you've just selected run/debug.

Edit your configuration and set the working directory explicitly to the directory containing your .env file - this is usually a level up from your module directory.

Example of configuration values for working directory in PyCharm dialog

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 MatsLindh