How to pass environment variables to Python runtime?

Sergey Royz
1 min readMay 2, 2023

The problem

os.environ["VAR_NAME"] should be set in runtime but without using of load_dotenv() .

Why not using load_dotenv() ? Because multiple .env.(local|test|dev) files may be present and the filename should not be hard coded. Also I don’t want to have code like this:

if os.environ('ENV') == 'test':
env_file = 'env.test'
elif os.environ('ENV') == 'dev':
env_file = 'env.dev'
...

One of possible solutions is to have export statement inside the .env.* files, e.g.:

export VAR_NAME=value

But it’s not compatible with load_dotenv() syntax, I still want to keep the possibility to use it, just in case.

The solution

export $(echo $(cat .env | sed 's/#.*//g'| xargs) | envsubst); python -m app.my_module

It loads .env file, exports all variables and adds them into the bash session where python application will be running.

P.S. checkout my pet-project, a simple file sharing service using QR-codes.

--

--

Sergey Royz

Co-founder and CTO of a crypto startup. A full-stack software engineer with a passion for creating innovative tech solutions that make a difference.