Working with INI files in Python

Quite often you want to extract you configuration data into a config file, the Windows INI is still a popular format, well understood by most people who like to get their hands dirty on the command line.
When using ini files, you basically want to do 3 things

  • Pass the name of the config file as a command line arg, printing something useful if the arg is missing
  • Load the contents of the init file and use them

This little code snippet does the lot in one go

import configparser
import os.path
from optparse import OptionParser

config  = ["-c", "--config", "config", "Configuration File, INI format"]
parser = OptionParser()
parser.add_option(config[0], config[1], dest=config[2], help=config[3])
(options, args) = parser.parse_args()
if None == options.config:
    parser.print_help ()
    exit(0)
if not os.path.isfile(options.config):
    exit(0)
    parser.print_help ()

config_file = configparser.ConfigParser(interpolation=None)
config_file.read(options.config)

Basically, import the necessary libraries, then set up the Command Line arg, in this instance -c, but you can add more by calling add_option() with new values

Next call parser.parse_args() to parse the command line args passed to you app. If nothing is there, or ‘config’ is missing, or not a valid file, then bomb out print useful help text

Finally load the ini file by using ConfigParser. I use ‘interpolation=None’ so that the parser does not substitute variables inside the ini allowing me to use $ and other non alpha numeric characters where needed

Be Sociable, Share!

Your email address will not be published. Required fields are marked *