• This repository has been archived on 07/Apr/2024
  • Stars
    star
    367
  • Rank 116,257 (Top 3 %)
  • Language
    Python
  • License
    MIT License
  • Created over 4 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Run Typer scripts with completion, without having to create a package, using Typer CLI.

Typer CLI

Run Typer scripts with completion, without having to create a package, using Typer CLI.

Test Coverage Package version

There is an optional utility tool called Typer CLI, additional to Typer itself.

It's main feature is to provide completion in the Terminal for your own small programs built with Typer.

...without you having to create a complete installable Python package.

It's probably most useful if you have a small custom Python script using Typer (maybe as part of some project), for some small tasks, and it's not complex/important enough to create a whole installable Python package for it (something to be installed with pip).

In that case, you can install Typer CLI, and run your program with the typer command in your Terminal, and it will provide completion for your script.

You can also use Typer CLI to generate Markdown documentation for your own Typer programs 📝.


Documentation: https://typer.tiangolo.com/typer-cli/

Source Code for Typer CLI: https://github.com/tiangolo/typer-cli


Typer or Typer CLI

Typer is a library for building CLIs (Command Line Interface applications).

You use Typer in your Python scripts. Like in:

import typer


def main():
    typer.echo("Hello World")


if __name__ == "__main__":
    typer.run(main)

Typer CLI is a command line application to run simple programs created with Typer, with completion in your terminal 🚀.

You use Typer CLI in your terminal, to run your scripts (as an alternative to calling python directly). Like in:

$ typer my_script.py run

Hello World

But you never import anything from Typer CLI in your own scripts.

Usage

Install

Install Typer CLI:

$ python -m pip install typer-cli
---> 100%
Successfully installed typer-cli

That creates a typer command you can call in your terminal, much like python, git, or echo.

You can then install completion for it:

$ typer --install-completion

zsh completion installed in /home/user/.bashrc.
Completion will take effect once you restart the terminal.

Sample script

Let's say you have a script that uses Typer in my_custom_script.py:

from typing import Optional

import typer

app = typer.Typer()


@app.command()
def hello(name: Optional[str] = None):
    if name:
        typer.echo(f"Hello {name}")
    else:
        typer.echo("Hello World!")


@app.command()
def bye(name: Optional[str] = None):
    if name:
        typer.echo(f"Bye {name}")
    else:
        typer.echo("Goodbye!")


if __name__ == "__main__":
    app()

For it to work, you would also install Typer:

$ python -m pip install typer
---> 100%
Successfully installed typer

Run with Python

Then you could run your script with normal Python:

$ python my_custom_script.py hello

Hello World!

$ python my_custom_script.py hello --name Camila

Hello Camila!

$ python my_custom_script.py bye --name Camila

Bye Camila

There's nothing wrong with using Python directly to run it. And, in fact, if some other code or program uses your script, that would probably be the best way to do it.

⛔️ But in your terminal, you won't get completion when hitting TAB for any of the subcommands or options, like hello, bye, and --name.

Run with Typer CLI

Here's where Typer CLI is useful.

You can also run the same script with the typer command you get after installing typer-cli:

$ typer my_custom_script.py run hello

Hello World!

$ typer my_custom_script.py run hello --name Camila

Hello Camila!

$ typer my_custom_script.py run bye --name Camila

Bye Camila
  • Instead of using python directly you use the typer command.
  • After the name of the file, add the subcommand run.

✔️ If you installed completion for Typer CLI (for the typer command) as described above, when you hit TAB you will have completion for everything , including all the subcommands and options of your script, like hello, bye, and --name 🚀.

If main

Because Typer CLI won't use the block with:

if __name__ == "__main__":
    app()

...you can also remove it if you are calling that script only with Typer CLI (using the typer command).

Run other files

Typer CLI can run any script with Typer, but the script doesn't even have to use Typer at all.

Typer CLI could even run a file with a function that could be used with typer.run(), even if the script doesn't use typer.run() or anything else.

For example, a file main.py like this will still work:

def main(name: str = "World"):
    """
    Say hi to someone, by default to the World.
    """
    print(f"Hello {name}")

Then you can call it with:

$ typer main.py run --help
Usage: typer run [OPTIONS]

  Say hi to someone, by default to the World.

Options:
  --name TEXT
  --help       Show this message and exit.

$ typer main.py run --name Camila

Hello Camila

And it will also have completion for things like the --name CLI Option.

Run a package or module

Instead of a file path you can pass a module (possibly in a package) to import.

For example:

$ typer my_package.main run --help
Usage: typer run [OPTIONS]

Options:
  --name TEXT
  --help       Show this message and exit.

$ typer my_package.main run --name Camila

Hello Camila

Options

You can specify one of the following CLI options:

  • --app: the name of the variable with a Typer() object to run as the main app.
  • --func: the name of the variable with a function that would be used with typer.run().

Defaults

When your run a script with the Typer CLI (the typer command) it will use the app from the following priority:

  • An app object from the --app CLI Option.
  • A function to convert to a Typer app from --func CLI Option (like when using typer.run()).
  • A Typer app in a variable with a name of app, cli, or main.
  • The first Typer app available in the file, with any name.
  • A function in a variable with a name of main, cli, or app.
  • The first function in the file, with any name.

Generate docs

Typer CLI can also generate Markdown documentation for your Typer application.

Sample script with docs

For example, you could have a script like:

import typer

app = typer.Typer(help="Awesome CLI user manager.")


@app.command()
def create(username: str):
    """
    Create a new user with USERNAME.
    """
    typer.echo(f"Creating user: {username}")


@app.command()
def delete(
    username: str,
    force: bool = typer.Option(
        ...,
        prompt="Are you sure you want to delete the user?",
        help="Force deletion without confirmation.",
    ),
):
    """
    Delete a user with USERNAME.

    If --force is not used, will ask for confirmation.
    """
    if force:
        typer.echo(f"Deleting user: {username}")
    else:
        typer.echo("Operation cancelled")


@app.command()
def delete_all(
    force: bool = typer.Option(
        ...,
        prompt="Are you sure you want to delete ALL users?",
        help="Force deletion without confirmation.",
    )
):
    """
    Delete ALL users in the database.

    If --force is not used, will ask for confirmation.
    """
    if force:
        typer.echo("Deleting all users")
    else:
        typer.echo("Operation cancelled")


@app.command()
def init():
    """
    Initialize the users database.
    """
    typer.echo("Initializing user database")


if __name__ == "__main__":
    app()

Generate docs with Typer CLI

Then you could generate docs for it with Typer CLI.

You can use the subcommand utils.

And then the subcommand docs.

$ typer some_script.py utils docs

Options:

  • --name TEXT: The name of the CLI program to use in docs.
  • --output FILE: An output file to write docs to, like README.md.

For example:

$ typer my_package.main utils docs --name awesome-cli --output README.md

Docs saved to: README.md

Sample docs output

For example, for the previous script, the generated docs would look like:


awesome-cli

Awesome CLI user manager.

Usage:

$ awesome-cli [OPTIONS] COMMAND [ARGS]...

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:

  • create: Create a new user with USERNAME.
  • delete: Delete a user with USERNAME.
  • delete-all: Delete ALL users in the database.
  • init: Initialize the users database.

awesome-cli create

Create a new user with USERNAME.

Usage:

$ awesome-cli create [OPTIONS] USERNAME

Options:

  • --help: Show this message and exit.

awesome-cli delete

Delete a user with USERNAME.

If --force is not used, will ask for confirmation.

Usage:

$ awesome-cli delete [OPTIONS] USERNAME

Options:

  • --force / --no-force: Force deletion without confirmation. [required]
  • --help: Show this message and exit.

awesome-cli delete-all

Delete ALL users in the database.

If --force is not used, will ask for confirmation.

Usage:

$ awesome-cli delete-all [OPTIONS]

Options:

  • --force / --no-force: Force deletion without confirmation. [required]
  • --help: Show this message and exit.

awesome-cli init

Initialize the users database.

Usage:

$ awesome-cli init [OPTIONS]

Options:

  • --help: Show this message and exit.

License

Typer CLI, the same as Typer, is licensed under the terms of the MIT license.

More Repositories

1

fastapi

FastAPI framework, high performance, easy to learn, fast to code, ready for production
Python
73,897
star
2

full-stack-fastapi-template

Full stack, modern web application template. Using FastAPI, React, SQLModel, PostgreSQL, Docker, GitHub Actions, automatic HTTPS and more.
TypeScript
24,890
star
3

typer

Typer, build great CLIs. Easy to code. Based on Python type hints.
Python
14,943
star
4

sqlmodel

SQL databases in Python, designed for simplicity, compatibility, and robustness.
Python
13,694
star
5

uwsgi-nginx-flask-docker

Docker image with uWSGI and Nginx for Flask applications in Python running in a single container.
Python
2,986
star
6

uvicorn-gunicorn-fastapi-docker

Docker image with Uvicorn managed by Gunicorn for high-performance FastAPI web applications in Python with performance auto-tuning.
Python
2,699
star
7

asyncer

Asyncer, async and await, focused on developer experience.
Python
1,517
star
8

pydantic-sqlalchemy

Tools to convert SQLAlchemy models to Pydantic models
Python
1,173
star
9

nginx-rtmp-docker

Docker image with Nginx using the nginx-rtmp-module module for live multimedia (video) streaming.
Dockerfile
1,110
star
10

dockerswarm.rocks

Docker Swarm mode rocks! Ideas, tools and recipes. Get a production-ready, distributed, HTTPS served, cluster in minutes, not weeks.
Python
1,093
star
11

uwsgi-nginx-docker

Docker image with uWSGI and Nginx for applications in Python (as Flask) in a single container.
Python
646
star
12

uvicorn-gunicorn-docker

Docker image with Uvicorn managed by Gunicorn for high-performance web applications in Python with performance auto-tuning.
Python
628
star
13

full-stack

Full stack, modern web application generator. Using Flask, PostgreSQL DB, Docker, Swagger, automatic HTTPS and more.
Python
523
star
14

meinheld-gunicorn-flask-docker

Docker image with Meinheld and Gunicorn for Flask applications in Python.
Python
486
star
15

full-stack-fastapi-couchbase

Full stack, modern web application generator. Using FastAPI, Couchbase as database, Docker, automatic HTTPS and more.
Python
440
star
16

poetry-version-plugin

Poetry plugin for dynamically extracting the package version from a __version__ variable or a Git tag.
Python
361
star
17

fastapi-cli

Run and manage FastAPI apps from the command line with FastAPI CLI. 🚀
Python
287
star
18

blog-posts

Blog posts and related code by Sebastián Ramírez (@tiangolo)
Python
273
star
19

uvicorn-gunicorn-starlette-docker

Docker image with Uvicorn managed by Gunicorn for high-performance Starlette web applications in Python with performance auto-tuning.
Python
182
star
20

latest-changes

A GitHub Action to add latest changes after each PR merged automatically
Python
172
star
21

babun-docker

Use Docker Toolbox with Babun (Cygwin) in Windows
Shell
170
star
22

meinheld-gunicorn-docker

Docker image with Meinheld managed by Gunicorn for high-performance WSGI (Flask, Django, etc) web applications in Python with performance auto-tuning.
Python
165
star
23

docker-with-compose

Docker image with Docker Compose installed for CI.
Shell
158
star
24

node-frontend

Instrutctions to buid a frontend Docker image built with Node.js and then served with Nginx. Previously a Docker image.
Dockerfile
137
star
25

flask-frontend-docker

Minimal project generator with a Flask backend, a modern frontend (Vue, React or Angular), a Traefik load balancer with HTTPS, all based on Docker.
Vue
130
star
26

python-machine-learning-docker

Docker image with Python 3.6 and 3.7 using Conda, with CUDA variants. To serve as base image for Machine Learning projects.
Dockerfile
84
star
27

uvicorn-gunicorn-machine-learning-docker

Docker image for high-performance Machine Learning web applications. With Uvicorn managed by Gunicorn in Python 3.7 and 3.6, using Conda, with CUDA and TensorFlow variants.
Python
67
star
28

issue-manager

Automatically close issues that have a label, after a custom delay, if no one replies back.
Python
62
star
29

full-stack-flask-couchbase

Full stack, modern web application generator. Using Flask, Couchbase as database, Docker, Swagger, automatic HTTPS and more.
Python
59
star
30

label-approved

Label a Pull Request after a number of approvals
Python
34
star
31

full-stack-flask-couchdb

Full stack, modern web application generator. Using Flask, CouchDB as database, Docker, Swagger, automatic HTTPS and more.
Python
31
star
32

tiangolo

16
star
33

github-actions-sandbox

Not useful for you. It's just a sandbox GitHub repo for me to try out stuff and develop GitHub Actions.
Python
16
star
34

tiangolo.com

Python
16
star
35

docker-auto-labels

Generate each Docker constraint label in random nodes in the cluster.
Python
15
star
36

angular-docker-multi-stage-example

Angular in Docker with Nginx, supporting environments, built with multi-stage Docker builds
15
star
37

ngx-http-client

Angular (4.3+) HttpClientModule with parameter encodings compatible with back ends (Node.js, Python, PHP, etc)
TypeScript
11
star
38

compose-to-rancher

Convert Docker Compose V2 to Rancher compatible Docker Compose V1
Python
10
star
39

markdown-include-variants

Markdown extension to expand directives to include source example files to also include their variants. Only useful to tiangolo's projets. Don't use it. 😅
Python
9
star
40

wunderlist2csv

Convert from Wunderlist backup json file to a CSV file importable by TaskCoach
Python
6
star
41

anaconda_cluster_install

Automatically Install Anaconda Python in a cluster of machines, for a specified user.
Shell
5
star
42

bitbucket_issues_to_redmine_csv

Python
3
star