Typer使用
基本概念
Typer 是一个用于构建命令行应用程序的现代化 Python 库。它基于 Python 类型提示,使用简单直观的 API 来创建 CLI 应用。
安装
pip install typer
基本用法
1. 创建应用实例
import typer
app = typer.Typer()
2. 定义命令
@app.command()
def hello(name: str):
typer.echo(f"Hello, {name}!")
# 执行
python script.py "World"
# 输出
# Hello, hello!
3. 添加命令选项和参数
@app.command()
def greet(
name: str, # 必选参数
count: int = typer.Option(1, "--count", "-c"), # 可选参数
greeting: str = typer.Option("Hello", help="要使用的问候语") # 带帮助信息的选项
):
for _ in range(count):
typer.echo(f"{name} {greeting}")
# 执行
python script.py "Good" --count 3 --greeting "Morning"
# 输出
# Good Morning
# Good Morning
# Good Morning
4. 生成帮助文档
- 自动生成的帮助信息可通过
--help
查看 - 可以为命令和参数添加详细的帮助文档
高级特性
1. 子命令
users_app = typer.Typer()
app.add_typer(users_app, name="users")
@users_app.command("create")
def users_create(name: str):
typer.echo(f"Creating user: {name}")
# 执行
python script.py users create "John"
# 输出
# Creating user: John
2. 命令组
@app.command()
def config(
set: bool = typer.Option(False, "--set"),
get: bool = typer.Option(False, "--get"),
key: str = typer.Option(None),
value: str = typer.Option(None)
):
if set:
typer.echo(f"Setting config key '{key}' to '{value}'")
elif get:
typer.echo(f"Getting config key '{key}'")
# 执行
python script.py --set --key "some_key" --value "some_value"
# 输出
# Setting config key 'some_key' to 'some_value'
# 执行
python script.py --get --key "some_key"
# 输出
# Getting config key 'some_key'
3. 多个命令
如果存在多个命令,则需要加上对应命令的名称
@app.command()
def hello():
typer.echo("Hello World!")
@app.command()
def goodbye():
typer.echo("Goodbye!")
@app.command("Good-morning")
def morning():
typer.echo("Good Morning!")
# 执行
python script.py hello
python script.py goodbye
python script.py Good-morning
最后编辑于:2024 年 11 月 20 日 22:07