Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get all environment variables starting with specific prefix in python

I want to get all the environment variables starting with a specific prefix and save them (without prefix) into a dictionary. Is there any better way than getting all the os.environ variables and searching through them? I also need those to be merged with a config file, so if you know any library in python which is like Viper in go (which handles both environment variables and config files and merging of them with priority), it will be a huge help.

UPDATE:

my configs are not simple app config, they are users config with some structures in it, so it's not a simple key value pair. It also might be in different formats, such as YAML, INI, JSON, etc.

like image 877
no746 Avatar asked Oct 28 '25 09:10

no746


1 Answers

If you are reading the env vars from .env file or from terminal than environs package is the best

export KAFKA_HOST=kafka
export KAFKA_PORT=9092

Python code to read all the env variables starting with KAFKA_

from environs import Env
env = Env()
env.read_env()
with env.prefixed("KAFKA_"):
     print(env("HOST"))
     print(env("PORT"))
like image 161
Anurag Choudhary Avatar answered Oct 30 '25 15:10

Anurag Choudhary