Last Updated: February 25, 2016
·
2.275K
· eugeny

Editing config files with Python

Ever had to edit nasty config formats with indentation, line continuations, comments to be preserved? Me too, so now I'm sharing my experience in form of python-reconfigure library: https://github.com/Eugeny/reconfigure

Basically, it is an object mapping that binds Python objects to a config file.

For example,

>>> from reconfigure.configs import FSTabConfig
>>> from reconfigure.items.fstab import FilesystemData
>>>
>>> config = FSTabConfig(path='/etc/fstab')
>>> config.load()
>>> print config.tree
{
    "filesystems": [
        {
            "passno": "0",
            "device": "proc",
            "mountpoint": "/proc",
            "freq": "0",
            "type": "proc",
            "options": "nodev,noexec,nosuid"
        },
        {
            "passno": "1",
            "device": "UUID=dfccef1e-d46c-45b8-969d-51391898c55e",
            "mountpoint": "/",
            "freq": "0",
            "type": "ext4",
            "options": "errors=remount-ro"
        }
    ]
}
>>> tmpfs = FilesystemData()
>>> tmpfs.mountpoint = '/srv/cache'
>>> tmpfs.type = 'tmpfs'
>>> tmpfs.device = 'none'
>>> config.tree.filesystems.append(tmpfs)
>>> config.save()
>>> quit()
$ cat /etc/fstab
proc    /proc   proc    nodev,noexec,nosuid     0       0
UUID=dfccef1e-d46c-45b8-969d-51391898c55e / ext4 errors=remount-ro 0 1
none    /srv/cache      tmpfs   none    0       0

It has a whole bunch of config classes, always preserves comments and never damages the data if the file was syntactically correct, and often even if it was not.