argparse: some mutually exclusive arguments in required group

前端 未结 3 2381
难免孤独
难免孤独 2021-02-19 08:56

I have a set of arguments that can logically be separated in 2 groups:

  • Actions: A1, A2, A3, etc.
  • Informations:
3条回答
  •  臣服心动
    2021-02-19 09:10

    There's nothing hacky about verifying arguments after they've been parsed. Just collect them all in a single set, then confirm that it is not empty and contains at most one action.

    actions = {"a1", "a2", "a3"}
    informations = {"i1", "i2", "i3"}
    p = argparse.ArgumentParser()
    # Contents of actions and informations contrived
    # to make the example short. You may need a series
    # of calls to add_argument to define the options and
    # constants properly
    for ai in actions + informations:
        p.add_argument("--" + ai, action='append_const', const=ai, dest=infoactions)
    
    args = p.parse_args()
    if not args.infoactions:
        p.error("At least one action or information required")
    elif len(actions.intersection(args.infoactions)) > 1:
        p.error("At most one action allowed")
    

提交回复
热议问题