python code to manipulate ini-style config files

Sunday, October 26 2008 @ 04:22 PM GMT

Contributed by: robin

I wanted to be able to enable/disable yum repo files from a kickstart script. They are in "ini" file format, e.g.:

name=Extra Packages for Enterprise Linux 5 - $basearch

I have written some perl code to do this that uses the Config::IniFiles module. But, this is not included in perl core and so would require installation before it could be used.

python includes ini-style file manipulation with the ConfigParser module, so I've written a python script to use it.

Sample usage:

initool --file /etc/yum.repos.d/epel.repo --section epel --option enabled=0
initool --file /etc/yum.repos.d/epel.repo --section epel --del priority

Here's the code:

#!/usr/bin/env python
import ConfigParser
from optparse import OptionParser

def main():
    version = "1.0"
    usage = "usage: %prog [options]"
    parser = OptionParser(usage=usage, version=version )
    parser.add_option("-f", "--file", dest="filename",
                      help="use file FILE", metavar="FILE")
    parser.add_option("-s", "--section", dest="section",
                      help="use section SECTION", metavar="SECTION")
    parser.add_option("-o", "--option", dest="set_options", action="append",
                      help="set OPTION=VALUE", metavar="OPTION=VALUE")
    parser.add_option("-d", "--del", dest="del_options", action="append",
                      help="delete option OPTION", metavar="OPTION")
    (opts, args) = parser.parse_args()

    if opts.set_options is None and opts.del_options is None:
        parser.error("no action specified")
    if opts.filename is None:
        parser.error("no file specified")
    if opts.section is None:
        parser.error("no section specified")

    cfg = ConfigParser.ConfigParser()

    if opts.set_options is not None:
        for opt in opts.set_options:
             # opt should be in format NAME=VALUE;
             name, value = opt.split('=')
             cfg.set(opts.section, name, value)

    if opts.del_options is not None:
        for opt in opts.del_options:
             # opt is just NAME
             cfg.remove_option(opts.section, opt)

    cfgfile = open(opts.filename, 'wb')

if __name__ == "__main__":

Comments (0)