Python Language Parsing Command Line arguments Advanced example with docopt and docopt_dispatch


As with docopt, with [docopt_dispatch] you craft your --help in the __doc__ variable of your entry-point module. There, you call dispatch with the doc string as argument, so it can run the parser over it.

That being done, instead of handling manually the arguments (which usually ends up in a high cyclomatic if/else structure), you leave it to dispatch giving only how you want to handle the set of arguments.

This is what the dispatch.on decorator is for: you give it the argument or sequence of arguments that should trigger the function, and that function will be executed with the matching values as parameters.

"""Run something in development or production mode.

Usage: --development <host> <port> --production <host> <port> items add <item> items delete <item>

from docopt_dispatch import dispatch

def development(host, port, **kwargs):
    print('in *development* mode')

def development(host, port, **kwargs):
    print('in *production* mode')

@dispatch.on('items', 'add')
def items_add(item, **kwargs):
    print('adding item...')

@dispatch.on('items', 'delete')
def items_delete(item, **kwargs):
    print('deleting item...')

if __name__ == '__main__':