问题
The program should be executed as follows:
./interpret.py --help | --source=FILE1 [--stats=FILE2 [--vars] [--insts]]
the rules are:
--help has to be the only argument if passed
--source=FILE1 has to be provided and can't be passed like --source FILE1
if --vars or --insts is provided, then --stats=FILE2 has to be provided
the order of --vars and --insts matters, therefore has to be stored
multiple occurrence of an argument is forbidden
I have read multiple tutorials and SO answers, but they don't even remotly cover my problem. Managed to do the following:
# parses command line arguments
def parse_args():
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--source')
parser.add_argument('--stats')
parser.add_argument('--vars', action='count', default=0)
parser.add_argument('--insts', action='count', default=0)
parser.add_argument('--help', action='count', default=0)
try:
args = parser.parse_args()
catch SystemExit:
exit(ERR_PARAM)
if args.help > 0:
if args.source != None or args.stats != None or (args.help + args.vars + args.insts) != 1:
exit(ERR_PARAM)
manual()
exit(0)
if args.source == None:
exit(ERR_PARAM)
if args.vars > 1 or args.insts > 1:
exit(ERR_PARAM)
if (args.vars + args.insts) > 0 and args.stats == None:
exit(ERR_PARAM)
return args
The code has the following problems:
--source and --stats can be passed multiple times
--source and --stats can be passed like --source FILE1
the order of --vars --insts is not stored anywhere
来源:https://stackoverflow.com/questions/49506868/argparse-nested-optional-argument-force-arg-val-over-arg-val-single-occur