python - 使用全局选项解析 rsyncd 配置文件时出现 ConfigParser.MissingSectionHeaderError

标签 python rsync configparser

配置文件通常需要每个部分的部分标题。在 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.

最佳答案

我使用 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 - 使用全局选项解析 rsyncd 配置文件时出现 ConfigParser.MissingSectionHeaderError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22501121/

相关文章:

python - 确保测试用例可以删除它创建的临时目录

python - 如何在Python中使用configparser向ini添加节和值?

安装 Yosemite 后出现 Python configparser 错误

python - 错误 : Unable to find py4j, 您的 SPARK_HOME 可能未正确配置

python - PyYaml解析Yaml配置文件中的Environment变量

python - 从 SQLAlchemy 插入到 Postgres 数据库

python - 如何在 Python 中显示和解析 rsync 进度?

python - NLTK 无法找到 stanford-postagger.jar!设置 CLASSPATH 环境变量

hadoop - Flume 用例 - 将数据从只读文件夹推送到 HDFS

Python 2,配置解析器: retrieving the line number of a section/option