2024-05-23 17:40:18 发布
网友
如何将Python 2.7ConfigParser的内容打印到logging?
ConfigParser
logging
我能找到的唯一解决方案是写入一个临时文件并将该文件读回。我的另一个想法是从日志实用程序获取一个假的“文件句柄”,并将其传递给ConfigParser write方法,但我不知道如何从日志中获取这样的句柄。
由于这是Google的顶级搜索结果,我希望找到一个将ConfigParser实例的值打印到stdout的解决方案,这里有一行代码可以帮助所有未来的读者:
print({section: dict(config[section]) for section in config.sections()})
您应该能够创建写入日志的可写对象。类似的内容(如果希望保留字符串,也可以修改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:
由于这是Google的顶级搜索结果,我希望找到一个将
ConfigParser
实例的值打印到stdout的解决方案,这里有一行代码可以帮助所有未来的读者:print({section: dict(config[section]) for section in config.sections()})
您应该能够创建写入日志的可写对象。类似的内容(如果希望保留字符串,也可以修改ConfigLogger来保存它):
这将产生以下输出:
相关问题 更多 >
编程相关推荐