How to use argparse subparsers correctly?

后端 未结 1 1676
梦如初夏
梦如初夏 2020-12-08 13:16

I\'ve been searching through allot of the subparser examples on here and in general but can\'t seem to figure this seemingly simple thing out.

I have two var types o

相关标签:
1条回答
  • 2020-12-08 13:34

    Subparsers are invoked based on the value of the first positional argument, so your call would look like

    python test01.py A a1 -v 61
    

    The "A" triggers the appropriate subparser, which would be defined to allow a positional argument and the -v option.

    Because argparse does not otherwise impose any restrictions on the order in which arguments and options may appear, and there is no simple way to modify what arguments/options may appear once parsing has begun (something involving custom actions that modify the parser instance might work), you should consider replacing -t itself:

    import argparse
    
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(help='types of A')
    parser.add_argument("-v", ...)
    
    a_parser = subparsers.add_parser("A")
    b_parser = subparsers.add_parser("B")
    
    a_parser.add_argument("something", choices=['a1', 'a2'])
    

    Since -v is defined for the main parser, it must be specified before the argument that specifies which subparser is used for the remaining arguments.

    0 讨论(0)
提交回复
热议问题