[programming basics] Python configuration file reading library ConfigParser summary

Keywords: MySQL Python PostgreSQL Database

The Python ConfigParser tutorial shows you how to use ConfigParser to use configuration files in Python.

Article catalog

1 Introduction

ConfigParser is a python class that implements the basic configuration language for Python programs. It provides a structure similar to Microsoft Windows INI files. ConfigParser allows you to write Python programs that can be easily customized by end users.

The configuration file consists of key / value pairs of options. Section names are separated by the [] character. These key value pairs are separated by: or =. Comments begin with a or.

Please refer to:
https://docs.python.org/3/library/configparser.html

The python language environment used in this article is python3. The configparser package name in python2 and python3 is different.
configparser is the package name in python3
ConfigParser is the package name in python2

1.1 Python ConfigParser reading files

In the following example, we read configuration data from a file. configuration file db.ini The content is as follows. It consists of two parts of data.

[mysql]
host = localhost
user = user7
passwd = s$cret
db = ydb

[postgresql]
host = localhost
user = user8
passwd = mypwd$7
db = testdb

The following example reads the configuration data of MySQL and PostgreSQL.

import configparser

# Start ConfigParse
config = configparser.ConfigParser()
# Use read() to read the file.
config.read('db.ini')

# Accessing data from mysql section
host = config['mysql']['host']
user = config['mysql']['user']
passwd = config['mysql']['passwd']
db = config['mysql']['db']

print('MySQL configuration:')

print(f'Host: {host}')
print(f'User: {user}')
print(f'Password: {passwd}')
print(f'Database: {db}')

# Accessing data from the postgresql section
host2 = config['postgresql']['host']
user2 = config['postgresql']['user']
passwd2 = config['postgresql']['passwd']
db2 = config['postgresql']['db']

print('PostgreSQL configuration:')

print(f'Host: {host2}')
print(f'User: {user2}')
print(f'Password: {passwd2}')
print(f'Database: {db2}')
MySQL configuration:
Host: localhost
User: user7
Password: s$cret
Database: ydb
PostgreSQL configuration:
Host: localhost
User: user8
Password: mypwd$7
Database: testdb

1.2 sections in Python configparser

The configuration data is divided into sections. Read all sections and has in sections()_ Section () checks for the specified section.

import configparser

config = configparser.ConfigParser()
config.read('db.ini')

# Get section name
sections = config.sections()
print(f'Sections: {sections}')

sections.append('sqlite')

for section in sections:

    # Determine whether the section name exists
    if config.has_section(section):
      print(f'Config file has section {section}')
    else:
      print(f'Config file does not have section {section}')
Sections: ['mysql', 'postgresql']
Config file has section mysql
Config file has section postgresql
Config file does not have section sqlite

1.3 Python ConfigParser reading data from strings

Starting with Python 3.2, we can use read_ The string () method reads configuration data from a string.

import configparser

# String profile data
cfg_data = '''
[mysql]
host = localhost
user = user7
passwd = s$cret
db = ydb
'''

config = configparser.ConfigParser()
config.read_string(cfg_data)

host = config['mysql']['host']
user = config['mysql']['user']
passwd = config['mysql']['passwd']
db = config['mysql']['db']

print(f'Host: {host}')
print(f'User: {user}')
print(f'Password: {passwd}')
print(f'Database: {db}')
Host: localhost
User: user7
Password: s$cret
Database: ydb

1.4 Python ConfigParser reading data from the dictionary

Starting with Python 3.2, we can use read_ The dict () method reads configuration data from the dictionary.

import configparser

# Dictionary data
# The key is the section name and the value is a dictionary with the keys and values that exist in the section.
cfg_data = {
    'mysql': {'host': 'localhost', 'user': 'user7',
              'passwd': 's$cret', 'db': 'ydb'}
}

config = configparser.ConfigParser()
config.read_dict(cfg_data)

host = config['mysql']['host']
user = config['mysql']['user']
passwd = config['mysql']['passwd']
db = config['mysql']['db']

print(f'Host: {host}')
print(f'User: {user}')
print(f'Password: {passwd}')
print(f'Database: {db}')
Host: localhost
User: user7
Password: s$cret
Database: ydb

1.5 Python ConfigParser writing data

Configuration data can be written through the write() method. The following example writes configuration data to the db3.ini file.

import configparser

config = configparser.ConfigParser()

# Through add_section() function add key
config.add_section('mysql')

config['mysql']['host'] = 'localhost'
config['mysql']['user'] = 'user7'
config['mysql']['passwd'] = 's$cret'
config['mysql']['db'] = 'ydb'

# Write data
with open('db3.ini', 'w') as configfile:
    config.write(configfile)

db.ini The contents in are as follows:

[mysql]
host = localhost
user = user7
passwd = s$cret
db = ydb

1.6 Python ConfigParserj interpretation data

ConfigParser allows data to be interpreted in a configuration file. It uses the% () syntax. This example uses cfg.ini As follows:

[info]
users_dir= /home/ubuntu
name= Jano
home_dir= %(users_dir)s\%(name)s

We use interpolation to build home_dir. Note that the "s" character is part of the syntax. We will explain the data

import configparser

config = configparser.ConfigParser()
config.read('cfg.ini')

users_dir = config['info']['users_dir']
name = config['info']['name']
home_dir = config['info']['home_dir']

# Read user path
print(f'Users directory: {users_dir}')
# Read user name
print(f'Name: {name}')
# Read full path
print(f'Home directory: {home_dir}')
Users directory: /home/ubuntu
Name: Jano
Home directory: /home/ubuntu/Jano

2 reference

http://zetcode.com/python/configparser/

https://docs.python.org/3/library/configparser.html

https://www.cnblogs.com/plf-Jack/p/11170284.html

Posted by turboprop on Sun, 21 Jun 2020 02:23:45 -0700