【问题标题】:How to log the contents of a ConfigParser?如何记录 ConfigParser 的内容?
【发布时间】:2014-05-14 18:24:05
【问题描述】:

如何将 Python 2.7 ConfigParser 的内容打印到 logging

我能找到的唯一解决方案是写入一个临时文件并重新读取该文件。我的另一个想法是从日志记录实用程序获取一个假的“文件句柄”并将其传递给 ConfigParser 写入方法,但是我不知道如何获得这样的句柄表单日志记录。

【问题讨论】:

  • 令人震惊的是,即使在 2020 年,ConfigParser 也没有简单的方法来获取用于日志记录的所有值。所有答案都非常神秘或无法捕获所有配置(例如,迭代部分会跳过 [DEFAULT])。
  • @bsplosion 默认 Python 2 或 3 语法中的字典理解是晦涩难懂的?
  • @SeanPianka 更多 ConfigParser 旨在解析和访问配置值,对吧?然而,正如我在您回复的评论中提到的那样,您在 config.sections() 上使用 dict 理解的答案根本无法捕获 [DEFAULT] 部分 - 给它一个测试。真的不理想 - 配置值应该比这更透明。
  • 我同意——这种行为很奇怪!
  • write 方法使用类似文件的对象。 io.StringIO 是一个类似文件的对象。因此,写入 StringIO 对象,然后 StringIO.read() 将返回您要查找的字符串。

标签: python python-2.7 logging


【解决方案1】:

由于这是 Google 搜索结果中的热门搜索结果,我希望找到一种解决方案,将 ConfigParser 实例的值打印到标准输出,这里有一条线可以帮助所有未来的读者:

print({section: dict(config[section]) for section in config.sections()})

【讨论】:

  • 我不确定这是否是 python 2 vs 3 的东西,但在 Python 2.7 中,我不得不使用 config.items(section)。假设 pprint 已导入:pprint.pprint({section: dict(config.items(section)) for section in config.sections()})
  • 注意:由于某些未知原因,这不会捕获[DEFAULT] 部分。尽管[DEFAULT] 在获取值时必须作为一个部分访问,但ConfigParser 可能不认为 default 是它自己部分的一部分。
  • 另一种选择:config.write(sys.stdout)
【解决方案2】:

您应该能够创建写入日志的可写对象。像这样的东西(如果你想保留字符串,你可以修改 ConfigLogger 来保存它):

import ConfigParser
import logging

class ConfigLogger(object):
    def __init__(self, log):
        self.__log = log
    def __call__(self, config):
        self.__log.info("Config:")
        config.write(self)
    def write(self, data):
        # stripping the data makes the output nicer and avoids empty lines
        line = data.strip()
        self.__log.info(line)

config = ConfigParser.ConfigParser()
config.add_section("test")
config.set("test", "a", 1)
# create the logger and pass it to write
logging.basicConfig(filename="test.log", level=logging.INFO)
config_logger = ConfigLogger(logging)
config_logger(config)

这会产生以下输出:

INFO:root:Config:
INFO:root:[test]
INFO:root:a = 1
INFO:root:

【讨论】:

  • 啊,我明白了。那么只要传递给 ConfigParser.write 的对象有自己的 write 函数,它就会调用它吗?太糟糕了,您无法开箱即用地获取 INFO 日志写入器对象。
【解决方案3】:

只需使用 StringIO 对象和 configparser 的 write 方法。

看起来“打印”配置对象内容的唯一方法是ConfigParser.write,它采用类似文件的对象。 io.StringIO 是一个类似文件的对象。因此,将配置写入 StringIO 对象,然后将 StringIO 对象读入字符串。

import logging
import io
import configparser



if __name__ == "__main__":
    ini='''
[GENERAL]
station_id = station_id

[SERIAL PORTS]
serial_ports = 
    com1
    com2
    com3
'''
    cp = configparser.ConfigParser()
    cp.read_string(ini)
    with io.StringIO() as ss:
        cp.write(ss)
        ss.seek(0) # rewind
        logging.warning(ss.read())

输出

WARNING:root:[GENERAL]
station_id = station_id

[SERIAL PORTS]
serial_ports = 
    com1
    com2
    com3

【讨论】:

    猜你喜欢
    • 2011-04-09
    • 2011-12-24
    • 1970-01-01
    • 2021-06-06
    • 2014-02-11
    • 1970-01-01
    • 2012-07-01
    • 2013-11-24
    • 1970-01-01
    相关资源
    最近更新 更多