'How to log the contents of a ConfigParser?

How can I print the contents of a Python 2.7 ConfigParser to logging?

The only solution I can find is to write to a temporary file and read that file back in. Another idea I had was to get a fake "file handle" from the logging utility and pass that to the ConfigParser write method, but I don't know how to get such a handle form logging.



Solution 1:[1]

As this is the top Google search result and I was hoping to find a solution to print the values of the ConfigParser instance to stdout, here's a one-liner to help all future readers:

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

Solution 2:[2]

Just use a StringIO object and the configparser's write method.

It looks like the only method for "printing" the contents of a config object is ConfigParser.write which takes a file-like object. io.StringIO is a file-like object. So, write the config to the StringIO object and then read the StringIO object into a string.

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())

output:

WARNING:root:[GENERAL]
station_id = station_id

[SERIAL PORTS]
serial_ports = 
    com1
    com2
    com3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vinzee
Solution 2 shrewmouse