python argparse store --foo=bar as args.key='foo', args.value='bar'

前端 未结 2 1003
猫巷女王i
猫巷女王i 2021-01-23 13:59

I\'d like to parse a command line that has a mutually exclusive group of options. Normally, I\'d just use --foo bar which would produce, in the namespace, ar

2条回答
  •  闹比i
    闹比i (楼主)
    2021-01-23 14:58

    Subclassing Action is exactly what the developers expect you to do. Even the default, most common action, 'store' is a subclass, argparse._StoreAction. argparse._StoreTrueAction is a subclass of argparse._StoreConstAction, differing only in the default and const defaults.

    To deal with the missing attribute case you could initialize them in a couple of ways:

    set_defaults lets you define any defaults, regardless of whether any arguments use them or not. In the documentation that is used to add function objects to the namespace when using subparsers.

    parser.set_defaults(thing_key=None, thing=None)
    

    You could also create a namespace with the defaults, and pass that as an argument to parse_args.

    myNamespace = argparse.Namespace(thing_key=None, thing=None)
    parser.parse_args(names=myNamespace)
    

    If you don't want a foo=None default in the namespace, define its default as argparse.SUPPRESS.

提交回复
热议问题