I am trying to parse the command line arguments using argparse, and if the user specifies a yaml file for the config-file, add those arguments to the args from argparse
import argparse import yaml from pprint import pprint class CLI(object): def execute(self): self.create_parser() self.options = self.parse_args() pprint(self.options) def create_parser(self): self.parser = argparse.ArgumentParser() g = self.parser.add_argument_group('Device Targets') g.add_argument( '--config-file', dest='config_file', type=argparse.FileType(mode='r')) g.add_argument('--name', default=[], action='append') g.add_argument('--age', default=[], action='append') g.add_argument('--delay', type=int) g.add_argument('--stupid', dest='stupid', default=False, action='store_true') def parse_args(self): args = self.parser.parse_args() if args.config_file: data = yaml.load(args.config_file) delattr(args, 'config_file') for key, value in data.items(): if isinstance(value, list): for v in value: getattr(args, key, []).append(v) else: setattr(args, key, value) return args cli = CLI() cli.execute()
If my config-file has the following data:
name: [Jill, Bob] age: [21, 33] delay: 30
And I run my code like this:
python test.py --conf args.txt --name 'Mark'
I get this for the output:
Namespace(age=[21, 33], delay=30, name=['Mark', 'Jill', 'Bob'], stupid=False)
So, it works, but is it good code?