如何将ConfigParser的内容打印到我的日志中?

时间:2014-05-14 18:24:06

标签: python python-2.7 logging

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

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

3 个答案:

答案 0 :(得分:8)

由于这是Google搜索结果的首选,我希望找到一个解决方案,将ConfigParser实例的值打印到stdout,这里有一个单行程可以帮助所有未来的读者:

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

答案 1 :(得分: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:

答案 2 :(得分:1)

只需使用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
相关问题