简体   繁体   中英

is there a better way to combine 2 config files?

I want to take 2 config files: src + dst, and add all sections/options that does not exsist in dst, but exsist in src, to dst.

This is my take, is there a better way?

import argparse
import configparser
import os


def get_config(file_path):
    config = configparser.ConfigParser()
    config.read_file(open(file_path))
    return config

def add_src_2_dst(src_config, dst_config):
    for section in src_config.sections():
        if section in dst_config.sections():
            for k,v in src_config[section].items():
                if k not in dst_config[section].keys():
                    dst_config[section][k] = v
        else:
            dst_config[section] = src_config[section]
    return dst_config

def parse(args_ls):
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--source', help='source file path', required=True)
    parser.add_argument('-d', '--dest', help='dest file path', required=True)
    parser.add_argument('-o', '--output', help='path to save dst file', required=True)
    return parser.parse_args(args_ls)

def main(args_ls):
    args = parse(args_ls)
    src = get_config(args.source)
    dst = get_config(args.dest)
    dst = add_src_2_dst(src, dst)
    dst.write(open(args.output,'w+'))

if __name__ == '__main__':
    main(os.sys.argv[1:])

The setdefault() method might help you:

def add_src_2_dst(src, dst):
    for section in src.sections():
        dst.setdefault(section, src[section])
        for k, v in src[section].items():
            dst[section].setdefault(k, v)
    return dst

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM