Répondre au commentaire

How to parse configuration files in Python

There are several solutions to parse configuration files in Python.

These are usually text files contain a list of options with a name and a value, such as "port=8080" or "user: admin". More elaborate configuration files such as "INI files" on Windows contain sections to organize options. A section starts with a name between square brackets, such as "[section1]".

ConfigParser for INI files with sections

See http://docs.python.org/library/configparser.html

This parser is powerful, but it does not support simple configuration files without sections.

SimpleConfigParser for config files without sections

As Fredrik Lundh proposed on the python-dev mailing-list, it is quite simple to extend ConfigParser to support files without sections: http://mail.python.org/pipermail/python-dev/2002-November/029987.html

I have made a module called SimpleConfigParser based on that idea, that you can reuse in your own projects. See attached file below.

Sample usage:

import SimpleConfigParser
filename = 'sample_config_no_section.ini'
cp = SimpleConfigParser.SimpleConfigParser()
cp.read(filename)
print 'getoptionslist():', cp.getoptionslist()
for option in cp.getoptionslist():
    print "getoption('%s') = '%s'" % (option, cp.getoption(option))
print "hasoption('wrongname') =", cp.hasoption('wrongname')

 

ConfigObj for more advanced config files

ConfigObj is able to handle INI config files with sections and subsections, among other enhancements.

see http://www.voidspace.org.uk/python/configobj.html

ElementTree for XML config files

see http://www.decalage.info/en/python/etree

Custom config file parser

In fact it is very easy to create your own configuration file parser, thanks to Python string methods such as split() and strip(). For example the following function is able to parse simple configurations files and return a dictionary of parameters:

COMMENT_CHAR = '#'
OPTION_CHAR =  '='
 
def parse_config(filename):
    options = {}
    f = open(filename)
    for line in f:
        # First, remove comments:
        if COMMENT_CHAR in line:
            # split on comment char, keep only the part before
            line, comment = line.split(COMMENT_CHAR, 1)
        # Second, find lines with an option=value:
        if OPTION_CHAR in line:
            # split on option char:
            option, value = line.split(OPTION_CHAR, 1)
            # strip spaces:
            option = option.strip()
            value = value.strip()
            # store in dictionary:
            options[option] = value
    f.close()
    return options
 
options = parse_config('config.ini')
print options

 


 

Fichier attachéTaille
SimpleConfigParser-0.02.zip2.01 Ko

Répondre

Le contenu de ce champ ne sera pas montré publiquement.
  • Les adresses de pages web et de messagerie électronique sont transformées en liens automatiquement.
  • Allowed HTML tags: <a> <b> <address> <blockquote> <br> <caption> <center> <code> <dd> <del> <div> <dl> <dt> <em> <font> <h2> <h3> <h4> <h5> <h6> <hr> <i> <img> <li> <ol> <p> <pre> <span> <strong> <sub> <sup> <table> <tbody> <td> <tfoot> <th> <thead> <tr> <u> <ul> <tr>
  • Les lignes et les paragraphes vont à la ligne automatiquement.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. The supported tag styles are: <foo>, [foo].
  • Insérer [toc list: ol; title: Table of Contents; minlevel: 2; maxlevel: 3; attachments: yes;] pour afficher une table des matières déroulable de style MediaWiki. Tous les arguments sont optionnels.

Plus d'informations sur les options de formatage

By submitting this form, you accept the Mollom privacy policy.