命令行扩展,依赖click
import typer
app = typer.Typer()
@app.command()
def greet(name: str):
"""Greet the user by NAME."""
typer.echo(f"Hello, {name}!")
@app.command()
def add(a: int, b: int):
"""Add two numbers."""
result = a + b
typer.echo(f"The sum of {a} and {b} is {result}.")
if __name__ == "__main__":
# 使用括号 () 调用一个对象时,实际上是在调用该对象的 __call__ 方法。这种设计允许对象表现得像函数
app()
命令行执行:
python script.py greet John
python script.py add 1 3
把第一个参数识别为命令,后面的识别为参数