Reading in environment variables from an environment file Reading in environment variables from an environment file python python

Reading in environment variables from an environment file


I use Python Dotenv Library. Just install the library pip install python-dotenv, create a .env file with your environment variables, and import the environment variables in your code like this:

import osfrom dotenv import load_dotenvload_dotenv()MY_ENV_VAR = os.getenv('MY_ENV_VAR')

From the .env file:

MY_ENV_VAR="This is my env var content."

This is the way I do when I need to test code outside my docker system and prepare it to return it into docker again.


This could also work for you:

env_vars = []with open(env_file) as f:    for line in f:        if line.startswith('#') or not line.strip():            continue        # if 'export' not in line:        #     continue        # Remove leading `export `, if you have those        # then, split name / value pair        # key, value = line.replace('export ', '', 1).strip().split('=', 1)        key, value = line.strip().split('=', 1)        # os.environ[key] = value  # Load to local environ        env_vars.append({'name': key, 'value': value}) # Save to a listprint(env_vars);

In the comments you'll find a few different ways to save the env vars and also a few parsing options i.e. to get rid of leading export keyword. Another way would be to use the python-dotenv library. Cheers.


You can use ConfigParser. Sample example can be found here.

But this library expects your key=value data to be present under some [heading]. For example, like:

[mysqld]user = mysql  # Key with valuespid-file = /var/run/mysqld/mysqld.pidskip-external-lockingold_passwords = 1skip-bdb      # Key without valueskip-innodb