[英]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. 在rsyncd配置文件中,全局部分不需要显式地具有节头。 Example of an rsyncd.conf file: rsyncd.conf文件的示例:
[rsyncd.conf] [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
? 如何使用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.
I use itertools.chain
(Python 3): 我使用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.) ( source=filename
产生更好的错误消息,尤其是当您从多个配置文件中读取时。)
Alex Martelli provided a solution for using ConfigParser to parse similar files (which are section less files). Alex Martelli 提供了一个解决方案 ,使用ConfigParser来解析类似的文件(这是一个较少的文件)。 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. 您可以应用上述解决方案来解析rsyncd配置文件。
>>> 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/rsyncdpid.pid'), ...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.