如何在Typer多子命令CLI中集成单命令实例并免输命令?
Typer合并单命令CLI时实现直接调用子命令组
背景
使用Typer开发命令行工具时,单命令CLI(如cli_a.py)会被自动优化,无需输入命令即可直接调用;多命令CLI(如cli_b.py)则必须指定具体命令才能执行。但将两者合并为super_cli.py后,原本的单命令CLIcli_a需要额外输入main才能执行,不符合预期。
单命令CLI示例:cli_a.py
#!env python import typer app = typer.Typer() @app.command() def main(): print('This is the output of main') if __name__ == '__main__': app()
单独调用时无需指定命令:
$ ./cli_a.py This is the output of main
多命令CLI示例:cli_b.py
#!env python import typer app = typer.Typer() @app.command() def cmd1(): print('This is the output of cmd1') @app.command() def cmd2(): print('This is the output of cmd2') if __name__ == '__main__': app()
调用时必须指定命令:
$ ./cli_b.py cmd1 This is the output of cmd1
合并后的super_cli.py
#!env python import typer import cli_a import cli_b app = typer.Typer() app.add_typer(cli_a.app, name='cli_a') app.add_typer(cli_b.app, name='cli_b') if __name__ == '__main__': app()
此时cli_b表现正常,但cli_a需要输入不必要的额外命令main:
$ ./super_cli.py cli_a main This is the output of main
直接调用cli_a会报错:
$ ./super_cli.py cli_a Usage: super_cli.py cli_a [OPTIONS] COMMAND [ARGS]... Try 'super_cli.py cli_a --help' for help. ╭─ Error ─────────────────────────────────────────────────────────────────────╮ │ Missing command. │ ╰─────────────────────────────────────────────────────────────────────────────╯
解决方案
只需修改cli_a.py,将原@app.command()装饰器替换为@app.callback(),把main函数设置为该Typer实例的回调函数:
修改后的cli_a.py
#!env python import typer app = typer.Typer() @app.callback() def main(): print('This is the output of main') if __name__ == '__main__': app()
验证效果
修改后super_cli.py无需改动,直接调用即可得到预期结果:
$ ./super_cli.py cli_a This is the output of main
同时cli_a.py单独运行的行为保持不变:
$ ./cli_a.py This is the output of main
原理说明
Typer中,@app.callback()定义的函数是命令组的默认执行逻辑,当用户未指定任何子命令时会自动触发。将原单命令的命令函数改为回调后,无论是单独运行cli_a.py,还是作为子命令组加入super_cli.py,都会在无额外命令时自动执行该逻辑,完美解决问题。
内容的提问来源于stack exchange,提问作者Andre Alexander Bell
相关产品推荐
相关产品推荐

