Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

[rsyncd.conf]

# GLOBAL OPTIONS

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

# MODULE OPTIONS
[mod1]
...

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

>>> import ConfigParser
>>> cp = ConfigParser.ConfigParser()
>>> cp.read("rsyncd.conf")

# Error: ConfigParser.MissingSectionHeaderError: File contains no section headers.
like image 465
Pranjal Mittal Avatar asked Mar 19 '14 09:03

Pranjal Mittal


1 Answers

I use itertools.chain (Python 3):

import configparser, itertools
cfg = configparser.ConfigParser()
filename = 'foo.ini'
with open(filename) as fp:
  cfg.read_file(itertools.chain(['[global]'], fp), source=filename)
print(cfg.items('global'))

(source=filename results in better error messages, especially if you read from multiple config files.)

like image 100
johnLate Avatar answered Sep 23 '22 09:09

johnLate