Typer 命令行工具使用示例

Typer 命令行工具使用示例

示例1:简单问候程序

代码

python 复制代码
import typer

app = typer.Typer()

@app.command()
def greet(name: str):
    """简单的问候命令"""
    typer.echo(f"Hello {name}!")

if __name__ == "__main__":
    app()

使用方式

bash 复制代码
# 输入
python simple_greet.py John

# 输出
Hello John!

示例2:带选项的问候程序

代码

python 复制代码
import typer

app = 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()

使用方式

bash 复制代码
# 输入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:复杂问候程序(用户提供的示例)

代码

python 复制代码
import typer
from typing import Optional

app = 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()

使用方式

bash 复制代码
# 输入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.

总结

  1. 位置参数 :直接声明,如 name: str
  2. 可选参数 :使用 Optionaltyper.Argument,如 age: Optional[int] = typer.Argument(None)
  3. 选项参数 :使用 typer.Option,可以设置短选项和长选项
  4. 帮助文档 :自动生成,可通过 --help 查看
  5. 参数顺序:位置参数必须按顺序提供,选项参数可以任意顺序

Typer 让创建功能丰富的命令行工具变得简单直观,只需使用 Python 类型提示即可自动处理参数解析和验证。

相关推荐
编程武士6 分钟前
从50ms到30ms:YOLOv10部署中图像预处理的性能优化实践
人工智能·python·yolo·性能优化
我的xiaodoujiao30 分钟前
Windows系统Web UI自动化测试学习系列2--环境搭建--Python-PyCharm-Selenium
开发语言·python·测试工具
傻啦嘿哟3 小时前
Python SQLite模块:轻量级数据库的实战指南
数据库·python·sqlite
Q_Q5110082853 小时前
python+django/flask+uniapp基于微信小程序的瑜伽体验课预约系统
spring boot·python·django·flask·uni-app·node.js·php
XueminXu3 小时前
Python读取MongoDB的JSON字典和列表对象转为字符串
python·mongodb·json·pymongo·mongoclient·isinstance·json.dumps
techdashen3 小时前
12分钟讲解Python核心理念
开发语言·python
jie*3 小时前
小杰机器学习(nine)——支持向量机
人工智能·python·机器学习·支持向量机·回归·聚类·sklearn
闭着眼睛学算法3 小时前
【华为OD机考正在更新】2025年双机位A卷真题【完全原创题解 | 详细考点分类 | 不断更新题目 | 六种主流语言Py+Java+Cpp+C+Js+Go】
java·c语言·javascript·c++·python·算法·华为od
郝学胜-神的一滴4 小时前
谨慎地迭代函数所收到的参数 (Effective Python 第31条)
开发语言·python·程序人生·软件工程
没有梦想的咸鱼185-1037-16635 小时前
【遥感技术】从CNN到Transformer:基于PyTorch的遥感影像、无人机影像的地物分类、目标检测、语义分割和点云分类
pytorch·python·深度学习·机器学习·数据分析·cnn·transformer