How to use argparse subparsers correctly?

Solution 1:

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.