Python command line tool - Python Typer Tutorial

Typer

What is Typer and Typer-Cli

Typer is a library that allows you to easily build CLI applications.

Typer-Cli is an optional utility to add tab-completion to your scripts.

Installing and enabling Typer

Install Typer

python -m pip install typer

Here is the application that I create in the video. As you can see we import typer, create an object of 'app' and then define some functions and add a decorator to the function to enable them as Typer commands.

A multi-command application

import typer

app = typer.Typer()

@app.command()
def hello(name: str):
    typer.echo(f"Hello {name}")

@app.command()
def goodbye(name: str, iq: int, display_iq: bool = False):
    if display_iq:
        typer.echo(f"Goodbye {name} who has {iq} IQ ")
    else:
        typer.echo(f"Goodbye {name}")


if __name__ == "__main__":
    app()

Auto completion using Typer-Cli

Instead of packaging your app, you could make use of typer-cli for autocompletion.

Installing and enabling Typer-Cli

Install Typer-CLI

python -m pip install typer-cli

Enable auto completion for your terminal (It will auto-detect)

typer --install-completion

Running app with Typer-Cli

Here is an example of how to run the script using Typer-CLI

typer .\main.py run goodbye

Resources:

https://typer.tiangolo.com/