You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Python Typer按定义顺序显示命令而非字母序?

解决Typer命令按定义顺序显示的问题

Typer基于Click框架实现,而Click默认会将命令按字母顺序排序展示。要让命令按定义顺序显示,可通过自定义Typer子类的方式实现:

实现步骤

  • 自定义OrderedTyper类继承自typer.Typer,维护一个列表记录命令注册的顺序
  • 重写command装饰器,每次注册命令时记录命令名称
  • 重写get_commands方法,按注册顺序返回命令

完整代码示例

import typer

class OrderedTyper(typer.Typer):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.command_order = []

    def command(self, *args, **kwargs):
        def decorator(func):
            # 调用父类的command装饰器注册命令
            cmd = super().command(*args, **kwargs)(func)
            # 记录当前命令的名称
            self.command_order.append(cmd.name)
            return cmd
        return decorator

    def get_commands(self, ctx):
        # 按注册顺序返回命令列表
        return [self.commands[name] for name in self.command_order if name in self.commands]

# 使用自定义的OrderedTyper创建应用
app = OrderedTyper()

@app.command()
def change_value(file_name: str, field: str):
    print(f"Here I will change the {file_name} {field}")

@app.command()
def close_field(file_name: str, field: str):
    print("I will close field")

@app.command()
def add_transaction(file_name: str):
    print("I will add the transaction")

if __name__ == "__main__":
    app()

验证效果

运行脚本后执行 python your_script.py --help,命令会按change_value → close_field → add_transaction的定义顺序展示,而非默认的字母序。

内容的提问来源于stack exchange,提问作者Swantewit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 20:25:06