一、简介
一个用于构建命令行界面(CLI)应用程序的Python库。该项目的主要目的是简化CLI应用程序的开发过程,提供易于使用的API和工具,以帮助用户快速构建高质量的CLI应用。typer支持多种特性,如数据验证、选项和参数的定义、命令的分组和组织、自动完成等.typer的使用可以简化CLI应用程序的开发过程,提高应用程序的可用性和可扩展性。
二、特点
• 写作直观:出色的编辑支持。完成无处不在。调试时间更短。设计为易于使用和学习。阅读文档的时间更少。
• 易于使用:对于最终用户来说,它很容易使用。自动帮助,并自动完成所有shell封装。
• 编写简洁:最大限度地减少代码重复。每个参数声明中有多个功能。更少的bug。
• 启动简单:最简单的例子只向应用程序添加2行代码:1个导入,1个函数调用。
• 易扩展:根据需要增加复杂性,创建任意复杂的命令树和子命令组,以及选项和参数。
• 运行脚本:Typer包括一个Typer命令/程序,您可以使用它来运行脚本,自动将它们转换为CLI,即使它们内部不使用Typer。
三、安装
通过命令pip进行安装:
pip install typer
四、快速入门
命令行窗口运行命令typer --help查看工具的命令行信息:
(venv) D:learn_typer>typer --help
Usage: typer [OPTIONS] [PATH_OR_MODULE] COMMAND [ARGS]...
Run Typer scripts with completion, without having to create a package.
You probably want to install completion for the typer command:
$ typer --install-completion
https://typer.tiangolo.com/
┌─ Arguments ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ path_or_module [PATH_OR_MODULE] [default: None] │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
┌─ Options ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ --app TEXT The typer app object/variable to use. [default: None] │
│ --func TEXT The function to convert to Typer. [default: None] │
│ --version Print version and exit. │
│ --install-completion Install completion for the current shell. │
│ --show-completion Show completion for the current shell, to copy it or customize the installation. │
│ --help Show this message and exit. │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
┌─ Commands ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ utils Extra utility commands for Typer apps. │
└──
1. 直接使用【代码中不引入】
这个脚本内部甚至不使用Typer,但是,您可以使用typer命令将其作为CLI应用程序运行。
# entry.py
import typer
def entry(name: str):
print(f"Hello {name}")
命令行通过typer运行命令typer 文件.py run:
• 可以通过命令typer 文件.py run --help查看运行程序的帮助信息
(venv) D:\learn_typer>typer entry.py run
Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME
Try 'typer [PATH_OR_MODULE] run --help' for help.
┌─ Error ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ Missing argument 'NAME'. │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
# 可以看到上面提示缺少必要参数name
(venv) D:\learn_typer>typer entry.py run beijing
Hello beijing
Tip:这种方式只支持脚本中只有一个函数,如果有多个,只会执行从上到下的第一个函数
2. 最简单的typer应用【脚本中引用】
2.1 添加命令行参数
# entry.py
import typer
def entry(name: str):
print(f"Hello {name}")
if __name__ == '__main__':
typer.run(entry)
命令行运行:
> python entry.py 张三
Hello 张三
Tip: 如果要求传入命令行参数【如上例的name】,但你想传空时,需要使用引号传一个空过去,如python entry.py "",如果要求传入多个参数,那么一定要按函数参数位置顺序传,程序是无法智能识别顺序的。
2.2 添加命令行选项
它与命令行参数最大的区别就是其前面多个--,然后其不受位置的限制,程序会默认去查找是否传了命令行选项,一般默认是可不传的(它都设置了默认值)
# test.py
import typer
def test(name: str, lastname: str, formal: bool = False):
if formal:
print(f"Good day mr.{name}{lastname}.")
else:
print(f"Hello {name}{lastname}")
if __name__ == '__main__':
typer.run(test)
运行帮助命令查看:
(venv) D:\learn_typer>python test.py --help
Usage: test.py [OPTIONS] NAME LASTNAME
在方法下添加说明,当使用--help时,会显示
使用此方法,需要传name和lastname两个参数 formal是一个命令行选项,不传时,默认为False
┌─ Arguments ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ * name TEXT [default: None] [required] │
│ * lastname TEXT [default: None] [required] │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
┌─ Options ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ --formal --no-formal [default: no-formal] │
│ --help Show this message and exit. │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
根据提示,可以看运行该程序,需要传入name与lastname两个命令行参数,然后还有2个选项--help是typer默认都有的,--formal是我们在函数中定义的,它的默认值是False,因为校验的是布尔值,typer会会自动创建一个正式-formal和一个非正式--no-formal,两个选项代表True和False。
(venv) D:\learn_typer>python 4.py --formal sun bei
Good day mr.sunbei.
(venv) D:\learn_typer>python 4.py sun bei
Hello sunbei
2.3 为命令行选项传值
本例中lastname设置了默认值,typer工具就会认为它是一个命令行选项
import typer
def test(name: str, lastname: str = "", formal: bool = False):
if formal:
print(f"Good day mr.{name}{lastname}.")
else:
print(f"Hello {name}{lastname}")
if __name__ == '__main__':
typer.run(test)
运行帮助查看:
(venv) D:learn_typer>python 5.py --help
Usage: 5.py [OPTIONS] NAME
┌─ Arguments ───────────────────────────────────────────────────────────────────────────────────┐
│ * name TEXT [default: None] [required] │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
┌─ Options ─────────────────────────────────────────────────────────────────────────────────────┐
│ --lastname TEXT │
│ --formal --no-formal [default: no-formal] │
│ --help Show this message and exit. │
└──
按要求执行:
(venv) D:\learn_typer>python 5.py sun
Hello sun
(venv) D:learn_typer>python 5.py sun --lastname xxx
Hello sunxxx
# 注意使用命令行选项就不受参数位置的影响
(venv) D:\learn_typer>python 5.py --lastname xxx --formal sun
Good day mr.sunxxx.
2.3 设置程序中断机制
当命令行接收到特定参数或标志时退出程序,不再执行后面的程序,使用typer.Exit()执行,使用typer.Exit(code=1)设置状态码,来告知程序执行实时出错,这个主要争对linux中执行命令,默认返回0,出现异常时返回1
# test.py
import typer
def main(username: str):
if username == "root":
print("The root user is reserved")
raise typer.Exit(code=1)
# 或者使用Abort,会在命令行上抛出Aborted.中止标识
# raise typer.Abort()
print(f"逻辑1: {username}")
print(f"逻辑2: {username}")
运行命令,可以看到当输入root时,程序就终止了:
(venv) D:\learn_typer>python test.py xxx
逻辑1: xxx
逻辑2: xxx
(venv) D:\learn_typer>python test.py root
The root user is reserved
3. 构建命令行应用并且拥有子命令
使用git命令时,我们可以使用git remote查看远程仓库列表,加上-v就查仓库详细信息,加上add我们就可以添加远程仓库,像这样git remote命令的基础上又可以配置子命令的场景我们也可以通过typer来实现。
需求:假设实现两个命令,每个命令都有自己的子命令
1. 用户脚本
# users.py
import typer
app = typer.Typer()
@app.command()
def create(user_name: str):
print(f"Creating user: {user_name}")
@app.command()
def delete(user_name: str):
print(f"Deleting user: {user_name}")
if __name__ == "__main__":
app()
2. 元素项脚本
# items.py
import typer
app = typer.Typer()
@app.command()
def create(item: str):
print(f"Creating item: {item}")
@app.command()
def delete(item: str):
print(f"Deleting item: {item}")
@app.command()
def sell(item: str):
print(f"Selling item: {item}")
if __name__ == "__main__":
app()
3. 入口脚本
# entry.py
import typer
import items
import users
app = typer.Typer()
app.add_typer(users.app, name="users")
app.add_typer(items.app, name="items")
if __name__ == "__main__":
app()
运行命令分别查看单独的users,items和汇总的帮助查看:
(venv) D:\learn_typer>python entry.py --help
Usage: entry.py [OPTIONS] COMMAND [ARGS]...
┌─ Options ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ --install-completion Install completion for the current shell. │
│ --show-completion Show completion for the current shell, to copy it or customize the installation. │
│ --help Show this message and exit. │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
┌─ Commands ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ items │
│ users │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
(venv) D:\my_all_project\learn_Jupyter_notebook\learn_typer>python entry.py users --help
Usage: entry.py users [OPTIONS] COMMAND [ARGS]...
┌─ Options ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ --help Show this message and exit. │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
┌─ Commands ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ create │
│ delete │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
(venv) D:\learn_typer>python entry.py items --help
Usage: entry.py items [OPTIONS] COMMAND [ARGS]...
┌─ Options ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ --help Show this message and exit. │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
┌─ Commands ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ create │
│ delete │
│ sell │
└───
通过以上的示例,我们就可以实现类似git-remote命令的功能了.
最后我们通过typer可以做什么呢,可以构建一个自己的命令行工具,例如我们在实际工作中每次构建项目都要添加很多外部和内部的包,我们其实就可以通过typer来一键创建了。 这个大家可以试试。至于typer更多的功能,请查看官方文档:https://typer.tiangolo.com/features/
领取专属 10元无门槛券
私享最新 技术干货