Usage

There are 2 ways to use Incenp.Click-Shell: the decorator and the factory method.

Decorator

The easiest way to get going with Incenp.Click-Shell is with the Click-style decorator. @incenp.click_shell.shell is meant to replace Click’s @click.group decorator for the root level of your app. In fact, the object generated by @incenp.click_shell.shell is a incenp.click_shell.core.Shell object, which is a subclass of click.core.Group.

import click
from incenp.click_shell import shell

# @click.group()  # no longer
@shell(prompt='my-app> ', intro='Starting my app...')
def my_app():
    pass

@my_app.command()
def testcommand():
    print('testcommand is running')

# more commands...

if __name__ == '__main__':
    my_app()

When the above program is run with a subcommand argument (e.g. testcommand), the original behaviour of Click is preserved, that is, the specified subcommand is executed:

$ python my_app.py testcommand
testcommand is running

When the same program is invoked without a subcommand argument, then instead of being shown the help message, the user is thrown into an interactive shell from which she can invoke the available subcommands:

$ python my_app.py
Starting my app...
my-app> testcommand
testcommand is running
my-app>

@incenp.click_shell.shell takes 4 arguments:

  • prompt - this will get printed as the beginning of each line in the shell. This can be a callable that will be called each time a prompt is printed. If the callable takes an argument named ctx, the click context will be passed in as that argument. Defaults to '(Cmd) '

  • intro - this will get printed once when the shell first starts. Defaults to None, meaning nothing gets printed.

  • hist_file - this is the location of the history file used by the shell. Defaults to '~/.click-history'.

  • on_finished - a callable that will be called when the shell exits. You can use it to clean up any resources that may need cleaning up.

@incenp.click_shell.shell also takes arbitrary keyword arguments, and they are passed on directly to the constructor for the incenp.click_shell.Shell` class.

Factory method

If you’d rather not use decorators (or can’t for some reason), you can manually create a shell object and start it up:

import click
from incenp.click_shell import make_click_shell

@click.group()
@click.pass_context
def my_app(ctx):
    pass

# Somewhere else in your code (as long as you have access to the
# root level Context object)

shell = make_click_shell(ctx, prompt='my-app> ',
                         intro='Starting my app...')
shell.cmdloop()

The first argument passed to make_click_shell must be the root level context object for your click application. The other 3 args (prompt, intro, hist_file) are the same as described above under the Decorator section.