Typer 命令行工具使用示例
示例1:簡單問候程序
代碼
import typerapp = typer.Typer()@app.command()
def greet(name: str):"""簡單的問候命令"""typer.echo(f"Hello {name}!")if __name__ == "__main__":app()
使用方式
# 輸入
python simple_greet.py John# 輸出
Hello John!
示例2:帶選項的問候程序
代碼
import typerapp = typer.Typer()@app.command()
def greet(name: str,formal: bool = typer.Option(False, "--formal", "-f", help="使用正式問候")
):"""帶選項的問候命令"""if formal:typer.echo(f"Good day, {name}.")else:typer.echo(f"Hello {name}!")if __name__ == "__main__":app()
使用方式
# 輸入1
python option_greet.py Alice# 輸出1
Hello Alice!# 輸入2
python option_greet.py Alice --formal# 輸出2
Good day, Alice.# 輸入3
python option_greet.py --help# 輸出3
Usage: option_greet.py [OPTIONS] NAME帶選項的問候命令Arguments:NAME [required]Options:--formal, -f 使用正式問候 [default: False]--help Show this message and exit.
示例3:復雜問候程序(用戶提供的示例)
代碼
import typer
from typing import Optionalapp = typer.Typer()@app.command()
def main(name: str,age: Optional[int] = typer.Argument(None, help="用戶的年齡"),formal: bool = typer.Option(False, "--formal", "-f", help="使用正式問候"),times: int = typer.Option(1, "--times", "-t", help="問候次數")
):"""一個簡單的問候程序"""greeting = f"Good day, {name}" if formal else f"Hello {name}"if age:greeting += f", you are {age} years old"for _ in range(times):typer.echo(greeting)if __name__ == "__main__":app()
使用方式
# 輸入1 - 基本問候
python complex_greet.py John# 輸出1
Hello John# 輸入2 - 帶年齡的問候
python complex_greet.py John 25# 輸出2
Hello John, you are 25 years old# 輸入3 - 正式問候
python complex_greet.py John --formal# 輸出3
Good day, John# 輸入4 - 多次問候
python complex_greet.py John --times 3# 輸出4
Hello John
Hello John
Hello John# 輸入5 - 組合所有選項
python complex_greet.py John 25 --formal --times 2# 輸出5
Good day, John, you are 25 years old
Good day, John, you are 25 years old# 輸入6 - 查看幫助
python complex_greet.py --help# 輸出6
Usage: complex_greet.py [OPTIONS] NAME [AGE]一個簡單的問候程序Arguments:NAME [required][AGE] 用戶的年齡Options:--formal, -f 使用正式問候 [default: False]--times, -t INTEGER 問候次數 [default: 1]--help Show this message and exit.
總結
- 位置參數:直接聲明,如
name: str
- 可選參數:使用
Optional
和typer.Argument
,如age: Optional[int] = typer.Argument(None)
- 選項參數:使用
typer.Option
,可以設置短選項和長選項 - 幫助文檔:自動生成,可通過
--help
查看 - 參數順序:位置參數必須按順序提供,選項參數可以任意順序
Typer 讓創建功能豐富的命令行工具變得簡單直觀,只需使用 Python 類型提示即可自動處理參數解析和驗證。