【问题标题】:ConfigParser.MissingSectionHeaderError when parsing rsyncd config file with global options使用全局选项解析 rsyncd 配置文件时发生 ConfigParser.MissingSectionHeaderError
【发布时间】:2014-04-25 10:02:05
【问题描述】:

配置文件通常需要每个部分的部分标题。在rsyncd config 文件中,全局部分不需要明确具有部分标题。 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.

【问题讨论】:

    标签: python rsync configparser


    【解决方案1】:

    我使用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 会产生更好的错误消息,尤其是当您从多个配置文件中读取时。)

    【讨论】:

    • 不错!这解决了我的问题并教会了我一个不错的 Python 技巧。谢谢!
    【解决方案2】:

    Alex Martelli provided a solution 使用 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'), ...]
    

    【讨论】:

    • 随着configparser#readfp 的弃用,这个答案虽然很好,但很可能在未来的 Python 版本中停止工作。 itertools#chain 答案对于较新的 Python 版本可能是更好的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    • 2022-11-24
    相关资源
    最近更新 更多