Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep ConfigParser output files sorted

I've noticed with my source control that the content of the output files generated with ConfigParser is never in the same order. Sometimes sections will change place or options inside sections even without any modifications to the values.

Is there a way to keep things sorted in the configuration file so that I don't have to commit trivial changes every time I launch my application?

like image 239
JcMaco Avatar asked Jul 15 '09 21:07

JcMaco


People also ask

What is configuration parsing?

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

How does ConfigParser work in Python?

The configparser module has ConfigParser class. It is responsible for parsing a list of configuration files, and managing the parsed database. Return all the configuration section names. Return whether the given section exists.

What is .INI file in Python?

An INI file is a configuration file for computer software that consists of a text-based content with a structure and syntax comprising key–value pairs for properties, and sections that organize the properties.


2 Answers

Looks like this was fixed in Python 3.1 and 2.7 with the introduction of ordered dictionaries:

The standard library now supports use of ordered dictionaries in several modules. The configparser module uses them by default. This lets configuration files be read, modified, and then written back in their original order.

like image 187
Alexander Ljungberg Avatar answered Sep 23 '22 03:09

Alexander Ljungberg


If you want to take it a step further than Alexander Ljungberg's answer and also sort the sections and the contents of the sections you can use the following:

config = ConfigParser.ConfigParser({}, collections.OrderedDict)
config.read('testfile.ini')
# Order the content of each section alphabetically
for section in config._sections:
    config._sections[section] = collections.OrderedDict(sorted(config._sections[section].items(), key=lambda t: t[0]))

# Order all sections alphabetically
config._sections = collections.OrderedDict(sorted(config._sections.items(), key=lambda t: t[0] ))

# Write ini file to standard output
config.write(sys.stdout)

This uses OrderdDict dictionaries (to keep ordering) and sorts the read ini file from outside ConfigParser by overwriting the internal _sections dictionary.

like image 44
Erwin Vrolijk Avatar answered Sep 21 '22 03:09

Erwin Vrolijk