Typer 构建命令行利用

1. 摘要

Typer 是一个构建命令行程序的python包,它具备一下几个长处:

  1. 设计简略,学习成本低,破费更少的工夫debug
  2. 用户应用便捷,主动构建帮忙文档并适配所有shell
  3. 代码量低,缩小大量反复
  4. 起步简略,只需两行代码即可构建一个app

2. 装置

pip install "typer[all]"

3. 实例

  • 创立一个test_app命令,打印Hello + 参数
import typerapp = typer.Typer()@app.command()def test_app(name: str):    print(f"Hello {name}")if __name__ == "__main__":    app()
  • 打印帮忙文档

  • 测试

4. 用法简介

4.1. 命令

typer中,只有给每一个函数加上@app.command()装璜器,那么这个函数就成为了一个命令。

import typerapp = typer.Typer()@app.command()def test_1(name: str):    print(f"Hello {name}")@app.command()def test_2(age: int):    print(f"{age} years old")    if __name__ == "__main__":    app()
  • help

  • 测试

须要多少个命令,写多少个函数即可。

4.2. 参数

typer中,命令函数中的参数,就主动变成了命令的参数,因而用户很容易设置参数。

  • 将下面两个命令合并为一个
import typerapp = typer.Typer()@app.command()def test_cli(name: str, age: int):    print(f"Hello {name} \n age: {age}")if __name__ == "__main__":    app()
  • help文档

  • 测试

须要多少个命令参数,设置多少个函数参数即可

4.3. 子命令

例如git命令还存在git addgit commit 等,因而typer也反对给命令设置子命令。

  • 两个子命令
import typerapp = typer.Typer()sub1 = typer.Typer()app.add_typer(sub1, name="sub1")sub2 = typer.Typer()app.add_typer(sub2, name="sub2")@sub1.command("sub1")def sub1_item(space1: str):    print(f"Creating sub1: {sub1}")@sub2.command("sub2")def sub2_item(space1: str):    print(f"Creating sub1: {sub2}")if __name__ == "__main__":    app()
  • help文档

  • 子命令 sub1

以上只是对typer的根底介绍,typer还反对:

  1. 参数类型查看,默认设置,区间设置,交互式命令

  1. 黑白打印等

  1. 进度条

  1. 谬误揭示

5. 小结

Typer的长处和性能远不于此,本文次要对typer, 一个python中构建命令行程序的包,做了一个简要介绍,次要起抛砖引玉的作用,如果有这方面需要的小伙伴能够自行钻研。

往期举荐

本文由mdnice多平台公布