How to use top-level arguments with subparsers in argparse
Question: In Python's argparse, how do you implement top-level arguments while still
using commands implemented as subparsers?

I'm trying to implement a `--version` argument to show the program's version
number, but argparse is giving me `error: too few arguments` because I'm not
specifying a sub-command for one of the subparsers.

My code:

    
    
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-v', '--version',
        help='Show version.',
        action='store_true',
        default=False
    )
    subparsers = parser.add_subparsers(
        dest="command",
    )
    list_parser = subparsers.add_parser('list')
    parser.parse_args(['--version'])
    

the output:

    
    
    usage: myscript.py [-h] [-v] {list} ...
    myscript.py: error: too few arguments
    


Answer: If you only need version to work, you can do this:

    
    
    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-v', '--version',
        action='version',
        version='%(prog)s 1.0',
    )
    

Subparsers won't bother any more; the special `version` action is processed
and exits the script before the parser looks for subcommands.

