configparser in Python

Introduction

Consider the following situation: several scripts have to be able to run in different modes.

The mode can be set as a variable at the start of the script in each script. In that case, if the mode changes, the value of the variable has to be changed in every file.

If there are many such scripts, it takes a lot of manual work. It can be reduced in several ways: with environment variables, with extra scripts that do the replacement, by setting up IDE and by creating one configuration file shared by all of them.

In this article you can study an example of using the library configparser for working with configuration files.

Example

Consider the file settings.toml from which the operating mode has to be read.

[general] mode=robot

project/ |-- config.py `-- settings.toml

Although the files are in the same directory, I prefer to use os.path.dirname() to set the path to settings.toml you can study the reasons why I recommend this approach in the article « Python os.path»

# config.py import os from configparser import ConfigParser def get_mode( filename="settings.toml", section="general"): print("config.mode()") try: os.path.isfile(filename) print(f"file {filename} is found") except FileNotFoundError as e: print(e) # create a parser parser = ConfigParser() file_path = os.path.join(os.path.dirname(__file__), filename) print(parser.read(file_path)) if parser.has_section(section): params = parser.items(section) for param in params: if param[0] == "mode": mode = param[1] else: raise Exception(f"Section {section} not found in the {filename} file") return mode

Now in every script you can simply import config and determine the mode with the function get_mode() and if the mode changes, only one field has to be edited in settings.toml

import config mode = config.get_mode() if mode == "robot": def print(s: str): logger.info(s)

Banner image

A config for connecting to a database

In the article «Python and Postgres» you can study a simple example of connecting to a database with psycopg2

The credentials in that example are stored in the file database.toml and are read from it by the script config.py based on configparser while the connection itself is made by another script pg_demo.py

From the point of view of usage configparser the difference from the previous example is that several parameters are read and the result is written to a dictionary .

#!/usr/bin/python # config.py import os from configparser import ConfigParser def config(filename="database.toml", section="postgresql"): # create a parser parser = ConfigParser() file_path = os.path.join(os.path.dirname(__file__), filename) # read config file parser.read(file_path) # get section, default to postgresql db = {} if parser.has_section(section): params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception(f"Section {section} not found in the {filename} file") return db

Article author: Andrei Olegovich