Argparse: nested optional argument, force --arg=val over --arg val, single occurrence, optional argument order

本秂侑毒 提交于 2021-01-29 09:21:58

问题


The program should be executed as follows:

./interpret.py --help | --source=FILE1 [--stats=FILE2 [--vars] [--insts]]

the rules are:

  1. --help has to be the only argument if passed

  2. --source=FILE1 has to be provided and can't be passed like --source FILE1

  3. if --vars or --insts is provided, then --stats=FILE2 has to be provided

  4. the order of --vars and --insts matters, therefore has to be stored

  5. 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:

  1. --source and --stats can be passed multiple times

  2. --source and --stats can be passed like --source FILE1

  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!