我要取两个配置文件: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:])