Pranjal Mittal Pranjal Mittal - 7 months ago 57
Python Question

ConfigParser.MissingSectionHeaderError when parsing rsyncd config file with global options

A configuration file generally needs section headers for each section. In rsyncd config files a global section need not explicitly have a section header. Example of an rsyncd.conf file:



path = /data/ftp
pid file = /var/run/
syslog facility = local3
uid = rsync
gid = rsync
read only = true
use chroot = true


How to parse such config files using python
Doing the following gives an erorr:

>>> import ConfigParser
>>> cp = ConfigParser.ConfigParser()

# Error: ConfigParser.MissingSectionHeaderError: File contains no section headers.


Alex Martelli provided a solution for using ConfigParser to parse similar files (which are section less files). His solution is a file-like wrapper that will automatically insert a dummy section.

You can apply the above solution to parsing rsyncd config files.

>>> class FakeGlobalSectionHead(object):
...     def __init__(self, fp):
...         self.fp = fp
...         self.sechead = '[global]\n'
...     def readline(self):
...         if self.sechead:
...             try: return self.sechead
...             finally: self.sechead = None
...         else: return self.fp.readline()
>>> cp = ConfigParser()
>>> cp.readfp(FakeGlobalSectionHead(open('rsyncd.conf')))
>>> print(cp.items('global'))
[('path', '/data/ftp'), ('pid file', '/var/run/'), ...]