Getting Started#
Installation#
Installation is done via pip:
pip install -U click-repl
To install it from source:
pip install -U git+https://github.com/click-contrib/click-repl.git
Usage#
click-repl can be integrated with your click application in various ways. Each of them has their own benefits.
Use the
register_repl()function to add therepl()command to your click app.This is the traditional way to add a REPL to a click app. It just adds a click command to your group, that invokes the REPL.
1import click 2from click_repl import register_repl 3 4@click.group() 5def cli(): 6 pass 7 8@cli.command() 9def hello(): 10 click.echo("Hello world!") 11 12register_repl(cli, name='myrepl') 13cli()
But now, you can use
register_repl()as a decorator.1import click 2from click_repl import register_repl 3 4@register_repl(name='myrepl') 5@click.group() 6def cli(): 7 pass 8 9@cli.command() 10 11def hello(): 12 click.echo("Hello world!") 13 14cli()
$ my_app myrepl > hello Hello world! > :exit $ echo hello | my_app repl Hello World! $
Use the
ReplGroupclass in theclsparameter of thegroup()decorator.1import click 2from click_repl import ReplGroup 3 4@click.group( 5 cls=ReplGroup, 6 prompt='> ', 7 startup=lambda: print("Entering REPL..."), 8 cleanup=lambda: print("Exiting REPL...") 9) 10def cli(): 11 pass 12 13@cli.command() 14def hello(): 15 click.echo("Hello world!") 16 17register_repl(cli) 18cli()
$ my_app Entering REPL... > hello Hello world! > :q Exiting REPL... $
Invoke the
replfunction manually wherever as you want:1import click 2from click_repl import repl 3 4@click.group(invoke_without_command=True) 5@click.option('-i', '--interactive', is_flag=True) 6@click.pass_context 7def cli(ctx, interactive): 8 if interactive: 9 repl(ctx) 10 11@cli.command() 12def hello(): 13 click.echo("Hello world!") 14 15cli()
$ my_app -i > hello Hello world! > :q
Advanced Usage#
For more flexibility over how your REPL works, you can use the repl function, the
ReplGroup class (as shown above), instead of register_repl(). For example, in your app:
1import click
2from click_repl import repl
3from prompt_toolkit.history import FileHistory
4
5@click.group()
6def cli():
7 pass
8
9@cli.command()
10@click.pass_context
11def myrepl(ctx):
12 repl(ctx, prompt_kwargs={
13 'history': FileHistory('/etc/myrepl/myrepl-history'),
14 })
15
16cli()
Now, your custom myrepl command will be available on your CLI, which will start a REPL which has its history stored in
/etc/myrepl/myrepl-history and persist between sessions.
Any arguments that can be passed to the python-prompt-toolkit’s
PromptSession class can be passed in the prompt_kwargs argument and will be used when
instantiating your prompt.