argparse optional subparser (for --version) argparse optional subparser (for --version) python python

argparse optional subparser (for --version)


According to documentation, --version with action='version' (and not with action='store_true') prints automatically the version number:

parser.add_argument('--version', action='version', version='%(prog)s 2.0')


FWIW, I ran into this also, and ended up "solving" it by not using subparsers (I already had my own system for printing help, so didn't lose anything there).

Instead, I do this:

parser.add_argument("command", nargs="?",                    help="name of command to execute")args, subcommand_args = parser.parse_known_args()

...and then the subcommand creates its own parser (similar to a subparser) which operates only on subcommand_args.


This seems to implement the basic idea of an optional subparser. We parse the standard arguments that apply to all subcommands. Then, if anything is left, we invoke the parser on the rest. The primary arguments are a parent of the subcommand so the -h appears correctly. I plan to enter an interactive prompt if no subcommands are present.

import argparsep1 = argparse.ArgumentParser( add_help = False )    p1.add_argument( ‘–flag1′ )p2 = argparse.ArgumentParser( parents = [ p1 ] )s = p2.add_subparsers()p = s.add_parser( ‘group’ )p.set_defaults( group=True )( init_ns, remaining ) = p1.parse_known_args( )if remaining:    p2.parse_args( args = remaining, namespace=init_ns )else:    print( ‘Enter interactive loop’ )print( init_ns )