pythonparsingcommand-line-argumentsargparsesubcommand

Python: argument parser that handles global options to sub-commands properly


argparse fails at dealing with sub-commands receiving global options:

import argparse
p = argparse.ArgumentParser()
p.add_argument('--arg', action='store_true')
s = p.add_subparsers()
s.add_parser('test')

will have p.parse_args('--arg test'.split()) work,
but fails on p.parse_args('test --arg'.split()).

Anyone aware of a python argument parser that handles global options to sub-commands properly?


Solution

  • Give docopt a try:

    >>> from docopt import docopt
    
    >>> usage = """
    ... usage: prog.py command [--test]
    ...        prog.py another [--test]
    ... 
    ... --test  Perform the test."""
    
    >>> docopt(usage, argv='command --test')
    {'--test': True,
     'another': False,
     'command': True}
    
    >>> docopt(usage, argv='--test command')
    {'--test': True,
     'another': False,
     'command': True}