Skip to content

Instantly share code, notes, and snippets.

@dag
Created May 2, 2011 14:09
Show Gist options
  • Save dag/951655 to your computer and use it in GitHub Desktop.
Save dag/951655 to your computer and use it in GitHub Desktop.

Sketch of a Python API for command-line interfaces

Usage and short options from reST Option List in docstring

@command
def main(two=False):
    """usage: main [options]

    -2, --two  This option has two variants.

    """

Options map to function arguments via the long option name.

Decorator for type coercion

@command
@coerce(two=bool)
def main(two=False):
    """usage: main [options]

    -2, --two  This option has two variants.

    """

Parse command-line and map to function arguments

# Parse sys.args and call unconditionally
main.parse_args()

# Parse passed args
main.parse_args(args)

# Noop unless called in main script
main.parse_args(if_main=__name__)

Subcommands from definition lists

@command
@commit.bind
@update.bind
def main():
    """usage: ./script [program options] <command> [options]...

    commit, ci
        commit the specified files or all outstanding changes
    update, up
        update working directory (or switch revisions)
    """

… and allow multiple commands in a row …

./script ci -m "did stuff" up
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment