Python ConfigParser.MissingSectionHeaderError在使用全局选项解析rsyncd配置文件时出错
配置文件通常需要每个节的节头。在文件中,全局节不需要显式地具有节头。rsyncd.conf文件的示例: [rsyncd.conf]Python ConfigParser.MissingSectionHeaderError在使用全局选项解析rsyncd配置文件时出错,python,rsync,configparser,Python,Rsync,Configparser,配置文件通常需要每个节的节头。在文件中,全局节不需要显式地具有节头。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 u
# 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]
...
如何使用pythonConfigParser
解析此类配置文件?
执行以下操作将产生erorr:
>>> import ConfigParser
>>> cp = ConfigParser.ConfigParser()
>>> cp.read("rsyncd.conf")
# Error: ConfigParser.MissingSectionHeaderError: File contains no section headers.
Alex Martelli使用ConfigParser解析类似文件(无节文件)。
他的解决方案是一个类似文件的包装器,它将自动插入一个虚拟节
您可以将上述解决方案应用于解析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'), ...]
我使用
itertools.chain
(Python 3):
(
source=filename
会产生更好的错误消息,尤其是当您从多个配置文件中读取时。)Nice!这解决了我的问题,教会了我一个很好的Python技巧。谢谢随着configparser#readfp
的弃用,这个答案虽然很好,但在Python的未来版本中可能会停止工作。对于较新的Python版本来说,itertools\chain
答案可能是一个更好的解决方案。
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'))