Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 23405

Daniel Roy Greenfeld: TIL: Typer commands defaulting to help

$
0
0

If you save this code to cli.py:

importtyperapp=typer.Typer()@app.command()defcreate():"""Creates a user"""typer.echoint("Creating user")@app.command()defdelete():"""Deletes a user"""typer.echo("Deleting user")if__name__=="__main__":app()

and run it you get:

$pythoncli.pyUsage:cli.py[OPTIONS]COMMAND[ARGS]...Try'cli.py --help'forhelp.╭─Error────────────╮Missingcommand.╰────────────────────╯

That's not bad, but it forces you to request help before doing anything. Here's how it can be made so much better through the @app.callback command. See below:

importtyperapp=typer.Typer()# Setup the helper default@app.callback(invoke_without_command=True)defhelper(ctx:typer.Context):"""    Awesome CLI app"""ifctx.invoked_subcommandisNone:typer.echo(ctx.get_help())@app.command()defcreate():"""Creates a user"""typer.echoint("Creating user")@app.command()defdelete():"""Deletes a user"""typer.echo("Deleting user")if__name__=="__main__":app()

Now we get something as a default that really shows off the charm of typer:

$pythoncli.pyUsage:cli.py[OPTIONS]COMMAND[ARGS]...AwesomeCLIapp╭─Options─────────────────────────────────────────────────────────────────────────────────────────────────────╮--install-completion          Install completion for the current shell.                                       │--show-completion             Show completion for the current shell, to copy it or customize the installation.│--help                        Show this message and exit.                                                     │╰───────────────────────────────────────────────────────────────────────────────────────────────────────────────╯╭─Commands──────────────╮createCreatesauserdeleteDeletesauser╰─────────────────────────╯

Viewing all articles
Browse latest Browse all 23405

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>