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

问题描述 投票:0回答:1

我想获取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:])
python configuration-files
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.