如何不使用子命令,用装饰器创建带context_settings的Typer应用?
给无带子命令的Typer应用添加context_settings
你完全可以不用子命令,直接通过以下方式改造:
- 创建Typer实例时传入
context_settings参数 - 用
@app.command(name="")装饰主函数,让它成为根命令,无需输入子命令名即可运行
改造前的极简代码(使用typer.run)
import typer def main(name: str): typer.echo(f"Hello {name}!") if __name__ == "__main__": typer.run(main)
改造后的代码(添加context_settings且无子命令)
import typer from typing import Dict # 定义你需要的context_settings配置 context_settings: Dict[str, list] = {"help_option_names": ["-h", "--help"]} # 创建Typer实例时传入配置 app = typer.Typer(context_settings=context_settings) @app.command(name="") # 空name让函数作为根命令 def main(name: str): typer.echo(f"Hello {name}!") if __name__ == "__main__": app()
关键说明
- 给
@app.command()传入name=""后,被装饰的函数会作为根命令存在,运行脚本时直接执行python app.py 你的参数即可,不需要加上函数名作为子命令。 - Typer文档里展示的多命令场景确实用函数名当子命令,但单命令场景下通过空
name就能避免子命令,保持应用简洁。
内容的提问来源于stack exchange,提问作者Cornelius Roemer
相关产品推荐
相关产品推荐

