代码之家  ›  专栏  ›  技术社区  ›  CIsForCookies

有没有更好的方法组合2个配置文件?

  •  0
  • CIsForCookies  · 技术社区  · 6 年前

    我要取两个配置文件:src+dst,并将dst中不存在但src中不存在的所有节/选项添加到dst中。

    这是我的主意,有更好的办法吗?

    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:])
    
    0 回复  |  直到 6 年前
        1
  •  1
  •   FMc TLP    6 年前

    这个 setdefault() 方法可能会帮助您:

    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