How to use the ConfigParser module

I investigated the ConfigParser module that handles configuration files (ini files).

What is an INI file?

INI file-Wikipedia

Handling of INI files in Python

Python provides ConfigParser, a module that can read and write INI files as standard.

13.2. ConfigParser — Configuration File Parser — Python 2.7ja1 documentation

Sample Python 2 version (check_config.py)

So, I made the following tool as a sample. Runs on Python 2.7.

check_config.py



#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
check_config.py
Utility to check configuration file (ini file)

Caution!
Error checking is sloppy.
'''

import ConfigParser
import os
import sys


def show_config(ini):
    '''
Display all contents of the configuration file (excluding comments)
    '''
    for section in ini.sections():
        print '[%s]' % (section)
        show_section(ini, section)
    return


def show_section(ini, section):
    '''
View the contents of a particular section of the configuration file
    '''
    for key in ini.options(section):
        show_key(ini, section, key)
    return


def show_key(ini, section, key):
    '''
Display the contents of a specific key item (property) in a specific section of the configuration file
    '''
    print '%s.%s =%s' % (section, key, ini.get(section, key))
    return


def set_value(ini, section, key, value):
    '''
Change the contents of a specific key item (property) in a specific section of the configuration file
    '''
    ini.set(section, key, value)
    print 'set %s.%s =%s' % (section, key, ini.get(section, key))
    return


def usage():
    sys.stderr.write("Usage: %s inifile [section [key [value]]]\n" % sys.argv[0])
    return


if __name__ == '__main__':
    argc = len(sys.argv)
    if argc == 1:
        usage()
        sys.exit(1)

    #Read configuration file
    INI_FILE = sys.argv[1]
    ini = ConfigParser.SafeConfigParser()
    if os.path.exists(INI_FILE):
        ini.read(INI_FILE)
    else:
        sys.stderr.write('%s not found' % INI_FILE)
        sys.exit(2)

    if argc == 2:
        show_config(ini)
    elif argc == 3:
        show_section(ini, sys.argv[2])
    elif argc == 4:
        show_key(ini, sys.argv[2], sys.argv[3])
    elif argc == 5:
        set_value(ini, sys.argv[2], sys.argv[3], sys.argv[4])
        #Write to a file (Caution! In the current situation, comments and line breaks will be deleted)
        f = open(INI_FILE, "w")
        ini.write(f)
        f.close()
    else:
        usage()
        sys.exit(3)

    sys.exit(0)
#EOF

How to use

Well, as you can see from the source code, w

python


python check_config.py

When no argument is specified. Display usage (). It's a promised way of UNIX commands.

python


python check_config.py inifile

If there is only one argument. In the first argument, specify the file name of the INI file. Display the contents of inifile.

python


python check_config.py inifile section

If there are two arguments. In the second argument, specify the section of the INI file. View the contents of a particular section of an inifile.

python


python check_config.py inifile section key

If there are three arguments. In the third argument, specify the key item (key) of a specific section of the INI file. Shows the contents of a particular key item in a particular section of an inifile.

python


python check_config.py inifile section key value

If there are four arguments. In the 4th argument, specify the content (value) to be changed for the key item of the specific section of the INI file. Only this operation rewrites the INI file. Change a specific key item (key) of a specific section of the inifile to the content value.

Sample Python 3 version

Nowadays, the Python 2 version is ridiculous, so we have prepared the Python 3 version as well.

Runs on Python 3.5.

check_config.py



#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
check_config.py
Utility to check configuration file (ini file)

Caution!
Error checking is sloppy.
'''

import configparser
import os
import sys


def show_config(ini):
    '''
Display all contents of the configuration file (excluding comments)
    '''
    for section in ini.sections():
        print ("[" + section + "]")
        show_section(ini, section)
    return


def show_section(ini, section):
    '''
View the contents of a particular section of the configuration file
    '''
    for key in ini.options(section):
        show_key(ini, section, key)
    return


def show_key(ini, section, key):
    '''
Display the contents of a specific key item (property) in a specific section of the configuration file
    '''
    print (section + "." + key + " = " + ini.get(section, key))
    return


def set_value(ini, section, key, value):
    '''
Change the contents of a specific key item (property) in a specific section of the configuration file
    '''
    ini.set(section, key, value)
    print (section + "." + key + " = " + ini.get(section, key))
    return


def usage():
    sys.stderr.write("Usage: " + sys.argv[0] + " inifile [section [key [value]]]\n")
    return


if __name__ == '__main__':
    argc = len(sys.argv)
    if argc == 1:
        usage()
        sys.exit(1)

    #Read configuration file
    INI_FILE = sys.argv[1]
    ini = configparser.SafeConfigParser()
    if os.path.exists(INI_FILE):
        ini.read(INI_FILE, encoding='utf8')
    else:
        sys.stderr.write(INI_FILE + "Not found")
        sys.exit(2)

    if argc == 2:
        show_config(ini)
    elif argc == 3:
        show_section(ini, sys.argv[2])
    elif argc == 4:
        show_key(ini, sys.argv[2], sys.argv[3])
    elif argc == 5:
        set_value(ini, sys.argv[2], sys.argv[3], sys.argv[4])
        #Write to a file (Caution! In the current situation, comments and line breaks will be deleted)
        with open(INI_FILE, "w", encoding='utf8') as f:
            ini.write(f)
    else:
        usage()
        sys.exit(3)

    sys.exit(0)
#EOF

Recommended Posts

How to use the ConfigParser module
How to use the optparse module
How to use the generator
How to use the decorator
How to use the zip function
How to use the Raspberry Pi relay module Python
How to use Python's logging module
How to use the Spark ML pipeline
[Linux] How to use the echo command
How to use the Linux grep command
How to use the IPython debugger (ipdb)
How to use TouchDesigner Python's external module
How to use xml.etree.ElementTree
How to use Python-shell
How to use tf.data
How to use Seaboan
How to use image-match
How to use shogun
How to use Pandas 2
How to use Virtualenv
How to use numpy.vectorize
How to use pytest_report_header
How to use partial
How to use Bio.Phylo
How to use x-means
How to use WikiExtractor.py
How to use IPython
How to use virtualenv
How to use Matplotlib
How to use iptables
How to use TokyoTechFes2015
How to use dictionary {}
How to use Pyenv
How to use list []
How to use python-kabusapi
How to use OptParse
How to use return
How to use dotenv
How to use pyenv-virtualenv
How to use Go.mod
How to use imutils
How to use import
How to use the C library in Python
How to use the graph drawing library Bokeh
How to use the Google Cloud Translation API
How to use the NHK program guide API
How to use Qt Designer
How to use search sorted
[gensim] How to use Doc2Vec
python3: How to use bottle (2)
Understand how to use django-filter
[Python] How to use list 1
How to use FastAPI ③ OpenAPI
How to use Python argparse
How to use IPython Notebook
How to use Pandas Rolling
[Note] How to use virtualenv
How to use redis-py Dictionaries
Python: How to use pydub
[Python] How to use checkio
[Go] How to use "... (3 periods)"