Typer 构建命令行应用
![Typer](https://img-blog.csdnimg.cn/img_convert/aa33b55b6720b02e16e2bba28c80fa85.png)
1. 摘要
Typer[1] 是一个构建命令行程序的python包,它具有一下几个优点:
-
设计简单,学习成本低,花费更少的时间debug
-
用户使用便捷,自动构建帮助文档并适配所有
shell
-
代码量低,减少大量重复
-
起步简单,只需两行代码即可构建一个app
2. 安装
pip install "typer[all]"
3. 实例
-
创建一个 test_app
命令,打印Hello
+ 参数
import typer
app = typer.Typer()
@app.command()
def test_app(name: str):
print(f"Hello {name}")
if __name__ == "__main__":
app()
-
打印帮助文档
![alt](https://img-blog.csdnimg.cn/img_convert/5a2de3c2b0a321e1e1cebec621539eab.png)
-
测试
![alt](https://img-blog.csdnimg.cn/img_convert/8755ed848e8975d7622a11a1d88beda7.png)
4. 用法简介
4.1. 命令
typer
中,只要给每一个函数加上@app.command()
装饰器,那么这个函数就成为了一个命令。
import typer
app = 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
![alt](https://img-blog.csdnimg.cn/img_convert/07378e9e9173423e460da5e342290068.png)
-
测试
![alt](https://img-blog.csdnimg.cn/img_convert/183f05332e9511a58734a77f16f6b0dc.png)
需要多少个命令,写多少个函数即可。
4.2. 参数
typer
中,命令函数中的参数,就自动变成了命令的参数,因此用户很容易设置参数。
-
将上面两个命令合并为一个
import typer
app = typer.Typer()
@app.command()
def test_cli(name: str, age: int):
print(f"Hello {name} \n age: {age}")
if __name__ == "__main__":
app()
-
help文档
![alt](https://img-blog.csdnimg.cn/img_convert/ed712614c479fe06528f149116c425b8.png)
-
测试
![alt](https://img-blog.csdnimg.cn/img_convert/4957d849d52183d42e747c485096dfd4.png)
需要多少个命令参数,设置多少个函数参数即可
4.3. 子命令
例如git
命令还存在git add
和 git commit
等,因此typer
也支持给命令设置子命令。
-
两个子命令
import typer
app = 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文档
![alt](https://img-blog.csdnimg.cn/img_convert/6661f163e40cdd537fb7f95e1270840e.png)
-
子命令 sub1
![alt](https://img-blog.csdnimg.cn/img_convert/5b24dada74df8f038f91c79e67a8d201.png)
以上只是对typer
的基础介绍,typer
还支持:
-
参数类型检查,默认设置,区间设置,交互式命令
![3](https://img-blog.csdnimg.cn/img_convert/d17a472c46b079f9ea29139c0f27df68.png)
-
彩色打印等
![alt](https://img-blog.csdnimg.cn/img_convert/9c24e8fd5be3e46b313298c1301eb993.png)
-
进度条
![alt](https://img-blog.csdnimg.cn/img_convert/128ff4dd9290fd0510aae4cf1a6874f3.png)
-
错误提醒
![alt](https://img-blog.csdnimg.cn/img_convert/0f3a5bee966a608f4bb57d7c5f8d7058.png)
5. 小结
Typer
的优点和功能远不于此,本文主要对typer
, 一个python中构建命令行程序的包,做了一个简要介绍,主要起抛砖引玉的作用,如果有这方面需求的小伙伴可以自行研究。
往期推荐
参考资料
Typer doc: https://typer.tiangolo.com
本文由 mdnice 多平台发布