Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compare config files with configparser
#!/usr/bin/env python
import configparser
import itertools
import sys
from pprint import pprint
def compare_confs(src, dst):
src_conf = configparser.RawConfigParser()
dst_conf = configparser.RawConfigParser()
src_conf.read(src)
dst_conf.read(dst)
src_sections = set(src_conf.sections())
dest_sections = set(dst_conf.sections())
sections_diff = compare_sections(src_sections, dest_sections)
options_diff_list = [
result
for section in src_sections & dest_sections
for result in compare_options(src_conf[section], dst_conf[section])
]
options_diff = set(itertools.chain.from_iterable(options_diff_list))
return sections_diff | options_diff
def compare_options(src, dst):
src_opts = set([opts for opts in src])
dst_opts = set([opts for opts in dst])
src_opts_diff = src_opts - dst_opts
dst_opts_diff = dst_opts - src_opts
result = []
for item in src_opts_diff:
result.append("Destination config is missing '%s' option" % item)
for item in dst_opts_diff:
result.append("Source config is missing '%s' option" % item)
for item in src_opts & dst_opts:
if src.get(item) != dst.get(item):
result.append("Option '%s' differs between configs" % item)
yield result
def compare_sections(src, dst):
src_diff = src - dst
dst_diff = dst - src
result = set()
for item in src_diff:
result.add("Destination config is missing '%s' section" % item)
for item in dst_diff:
result.add("Source config is missing '%s' section" % item)
return result
def main():
if len(sys.argv) < 3:
print(
"Provide source and destination configs with positionall arguments"
)
raise SystemExit(1)
source = sys.argv[1]
dest = sys.argv[2]
diff = compare_confs(source, dest)
pprint(diff)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment