解析带有全局选项的rsyncd配置文件时出现ConfigParser.MissingSectionHeaderError

10 投票
2 回答
14033 浏览
提问于 2025-04-17 22:56

配置文件通常需要为每个部分添加标题。在 rsyncd 配置 文件中,全球部分不需要明确的标题。下面是一个 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]
...

如何使用 Python 的 ConfigParser 来解析这样的配置文件呢?如果这样做,会出现错误:

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

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

2 个回答

18

我使用的是 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 可以得到更好的错误提示,特别是当你从多个配置文件读取时。)

3

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'), ...]

撰写回答