Building Python CLI Applications with Typer: Subcommands, Auto‑Completion, and Automatic Documentation
This tutorial demonstrates how to install and use the Typer library to create Python command‑line interfaces with functions, subcommands, auto‑completion, and auto‑generated documentation, providing step‑by‑step code examples and usage instructions for developers.
The author, a fan of the FastAPI web framework, introduces the tiangolo organization and its companion project typer , a Python library for building command‑line interfaces.
Typer can be installed via python3 -m pip install typer .
In the first example, a file example_1.py is created with the following content:
import typer
def main(name: str, salary: int):
print(f'
{name}
月薪
{salary}
元')
if __name__ == '__main__':
typer.run(main)Running the script without arguments raises an error; using the --help flag shows the automatically generated CLI parameters.
The article then shows how to handle multiple commands (subcommands) by defining two functions, train_data and predict , each with its own arguments, and decorating them with @app.command() after creating a typer.Typer instance:
def train_data(train_folder: str, test_folder: str, rate: float = 0.8):
"""训练人脸检测模型"""
print(f'使用文件夹{train_folder}中的数据进行训练')
print(f'使用{test_folder}中的数据用来验证训练效果,确保准确率>{rate}')
return True
def predict(folder: str):
"""使用训练好的模型预测"""
print(f'对文件夹{folder}中的数据进行预测。')
app = typer.Typer(help="人脸检测模型")
@app.command()
def train_data(...):
...
@app.command()
def predict(...):
...With these definitions, the CLI supports commands such as typer example_2.py run train_data --train_folder data/train --test_folder data/test and typer example_2.py run predict --folder data/sample , and the --help flag can be used on each subcommand to view its specific options.
To enable shell auto‑completion, the auxiliary tool typer-cli is installed ( python3 -m pip install typer-cli ) and the completion script is added with typer --install-completion . After that, typing typer example_2.py run and pressing Tab suggests available subcommands.
Typer also provides automatic documentation generation similar to FastAPI. By defining the same commands in a Typer app, the following command creates a readme.md file with the CLI reference:
typer main.py utils docs --name "python3 main.py" --output readme.mdOpening the generated Markdown file shows a neatly formatted description of all commands and their parameters, eliminating the need for manual documentation upkeep.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.