fastapi:用typer创建命令行命令
一,安装所需的库
$ pip install typer
二,代码:

run_cli.py
# run_cli.py
import typer
from app.commands import calc_util
# 创建总的 Typer 实例
app = typer.Typer(help="基于typer的命令行实例")
# 像 FastAPI 的 include_router 一样,合并不同的命令组
app.add_typer(calc_util.app, name="calc_util", help="执行计算")
if __name__ == "__main__":
app()
app/commands/calc_util.py
# app/commands/calc_util.py
import typer
# 引入 Web 和 CLI 共用的业务逻辑
# from app.services.user_service import create_user_in_db
app = typer.Typer()
# 1. 使用装饰器定义另一个名为 "calc" 的命令
@app.command()
def calc1(x: int, y: int):
"""
计算两个整数的和。
"""
typer.echo(f"计算结果: {x} + {y} = {x + y}")
三,测试效果:
$ python run_cli.py calc_util calc1 3 4
计算结果: 3 + 4 = 7
浙公网安备 33010602011771号