argparse-cli


argparse-cli provides an introspection-based class-interface for argparse

This module requires argparse which is part of Python 2.7 and is available separately for older Python versions.

It automatically generates command line parsers from a class definition. This may not work for complex command line interfaces but gets the job done for common use cases.

Methods prefixed with do_ are translated into sub-commands, parameters without default value become positional arguments and parameters with default-values become optional parameters. Doc-strings are used for help texts. Additional help can be put in help-keyword-parameters. Global options can be specified with the setup-method.

Here is an example:

``` from argparse_cli import Cli

class Daemon(Cli): "this is an example daemon"

def setup(self, pidfile="~/.daemon.pid"): 
    self.pidfile = pidfile

def do_start(self, document_root): 
    "start daemon"

def do_stop(self, force=False, help={"force":"force stop"}): 
    "stop daemon"
    os.kill(int(open(self.pidfile).read()))

if name == "main": cli = Daemon() cli.run() ```

Calling the module without arguments:

# python demo.py
usage: demo.py [-h] [--pidfile [PIDFILE]] {start,stop} ...
demo.py: error: too few arguments`

Let's see the generated help:

# python demo.py --help
usage: demo.py [-h] [--pidfile [PIDFILE]] {start,stop} ...
this is an example daemon
positional arguments:
{start,stop} sub-command help
start start daemon
stop stop daemon
optional arguments:
-h, --help show this help message and exit
--pidfile [PIDFILE] default: '~/.daemon.pid'

Help for the start command:

# python demo.py start --help
usage: demo.py start [-h] [document_root]

positional arguments:
document_root

optional arguments:
-h, --help show this help message and exit

Help for the stop command:

# python demo.py stop --help
usage: demo.py [-h] [--pidfile [PIDFILE]] {start,stop} ...

this is an example daemon

positional arguments:
{start,stop} sub-command help
start start daemon
stop stop daemon

optional arguments:
-h, --help show this help message and exit
--pidfile [PIDFILE] default: '~/.daemon.pid'

Project Information

Labels:
python argparse optparse getopt command-line