繁体   English   中英

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

[英]is there a better way to combine 2 config files?

我想获取2个配置文件: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:])

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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