跳转到主要内容

Typer,构建优秀的命令行界面(CLI)。易于编写。基于Python类型提示。

项目描述

Typer

Typer,构建优秀的命令行界面(CLI)。易于编写。基于Python类型提示。

Test Publish Coverage Package version


文档: https://typer.fastapi.org.cn

源代码: https://github.com/fastapi/typer


Typer是一个用于构建用户喜爱使用、开发者喜爱创建的命令行界面(CLI)应用的库。基于Python类型提示。

它也是一个命令行工具,用于运行脚本,自动将它们转换为CLI应用。

其主要特性包括

  • 易于编写:优秀的编辑器支持。无处不在的自动完成(也称为自动补全、自动完成、IntelliSense)。减少调试时间。设计得易于使用和学习。减少阅读文档的时间。
  • 易于使用:对于最终用户来说很容易使用。自动帮助,所有外壳的自动完成。
  • 简洁:最小化代码重复。每个参数声明具有多个功能。更少的错误。
  • 从简单开始:最简单的示例只为您应用程序添加了2行代码: 1 个导入,1 次函数调用
  • 扩展性:根据需要扩展复杂性,创建任意复杂的命令树和子命令组,包括选项和参数。
  • 运行脚本:Typer包括一个typer命令/程序,您可以使用它来运行脚本,即使它们没有在内部使用Typer,也会自动将它们转换为CLIs。

CLIs的FastAPI

TyperFastAPI的小兄弟,它是CLIs的FastAPI。

安装

创建并激活一个虚拟环境,然后安装typer

$ pip install typer
---> 100%
Successfully installed typer rich shellingham

示例

最基本的内容

  • 创建一个文件main.py,包含以下内容:
def main(name: str):
    print(f"Hello {name}")

此脚本甚至没有在内部使用Typer。但您可以使用typer命令将其作为CLI应用程序运行。

运行它

使用typer命令运行您的应用程序

// Run your application
$ typer main.py run

// You get a nice error, you are missing NAME
Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME
Try 'typer [PATH_OR_MODULE] run --help' for help.
╭─ Error ───────────────────────────────────────────╮
│ Missing argument 'NAME'.                          │
╰───────────────────────────────────────────────────╯


// You get a --help for free
$ typer main.py run --help

Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME

Run the provided Typer app.

╭─ Arguments ───────────────────────────────────────╮
│ *    name      TEXT  [default: None] [required]   |
╰───────────────────────────────────────────────────╯
╭─ Options ─────────────────────────────────────────╮
│ --help          Show this message and exit.       │
╰───────────────────────────────────────────────────╯

// Now pass the NAME argument
$ typer main.py run Camila

Hello Camila

// It works! 🎉

这是一个最简单的用例,甚至没有在内部使用Typer,但它对于简单的脚本来说已经非常有用了。

注意:自动完成在您创建Python包并使用--install-completion运行它时工作,或者当您使用typer命令时。

在您的代码中使用Typer

现在让我们开始在自己的代码中使用Typer,更新main.py如下:

import typer


def main(name: str):
    print(f"Hello {name}")


if __name__ == "__main__":
    typer.run(main)

现在您可以直接使用Python运行它

// Run your application
$ python main.py

// You get a nice error, you are missing NAME
Usage: main.py [OPTIONS] NAME
Try 'main.py --help' for help.
╭─ Error ───────────────────────────────────────────╮
│ Missing argument 'NAME'.                          │
╰───────────────────────────────────────────────────╯


// You get a --help for free
$ python main.py --help

Usage: main.py [OPTIONS] NAME

╭─ Arguments ───────────────────────────────────────╮
│ *    name      TEXT  [default: None] [required]   |
╰───────────────────────────────────────────────────╯
╭─ Options ─────────────────────────────────────────╮
│ --help          Show this message and exit.       │
╰───────────────────────────────────────────────────╯

// Now pass the NAME argument
$ python main.py Camila

Hello Camila

// It works! 🎉

注意:您也可以使用typer命令调用此相同的脚本,但您不需要这样做。

示例升级

这是可能的最简单示例。

现在让我们看看一个稍微复杂一点的例子。

具有两个子命令的示例

修改文件main.py

创建一个typer.Typer()应用程序,并创建两个带有其参数的子命令。

import typer

app = typer.Typer()


@app.command()
def hello(name: str):
    print(f"Hello {name}")


@app.command()
def goodbye(name: str, formal: bool = False):
    if formal:
        print(f"Goodbye Ms. {name}. Have a good day.")
    else:
        print(f"Bye {name}!")


if __name__ == "__main__":
    app()

这将

  • 显式创建一个typer.Typer应用程序。
    • 之前的typer.run实际上为您隐式地创建了一个。
  • 使用@app.command()添加两个子命令。
  • 执行app()本身,就像它是一个函数一样(而不是typer.run)。

运行升级后的示例

查看新的帮助信息

$ python main.py --help

 Usage: main.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 ────────────────────────────────────────╮
│ goodbye                                           │
│ hello                                             │
╰───────────────────────────────────────────────────╯

// When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion

// You have 2 subcommands (the 2 functions): goodbye and hello

现在查看hello命令的帮助信息

$ python main.py hello --help

 Usage: main.py hello [OPTIONS] NAME

╭─ Arguments ───────────────────────────────────────╮
│ *    name      TEXT  [default: None] [required]   │
╰───────────────────────────────────────────────────╯
╭─ Options ─────────────────────────────────────────╮
│ --help          Show this message and exit.       │
╰───────────────────────────────────────────────────╯

现在查看goodbye命令的帮助信息

$ python main.py goodbye --help

 Usage: main.py goodbye [OPTIONS] NAME

╭─ Arguments ───────────────────────────────────────╮
│ *    name      TEXT  [default: None] [required]   │
╰───────────────────────────────────────────────────╯
╭─ Options ─────────────────────────────────────────╮
│ --formal    --no-formal      [default: no-formal] │
│ --help                       Show this message    │
│                              and exit.            │
╰───────────────────────────────────────────────────╯

// Automatic --formal and --no-formal for the bool option 🎉

现在您可以尝试运行新的命令行应用程序

// Use it with the hello command

$ python main.py hello Camila

Hello Camila

// And with the goodbye command

$ python main.py goodbye Camila

Bye Camila!

// And with --formal

$ python main.py goodbye --formal Camila

Goodbye Ms. Camila. Have a good day.

总结

总之,您只需将参数的类型(CLI参数CLI选项)作为函数参数声明一次。

您可以使用标准现代Python类型来完成此操作。

您不需要学习新的语法,特定库的方法或类等。

只是标准的Python

例如,对于int

total: int

或者对于bool标志

force: bool

同样适用于文件路径枚举(选择)等。并且有工具可以创建子命令组、添加元数据、额外的验证等。

您获得:优秀的编辑器支持,包括自动完成类型检查

您的用户将获得:自动 --help,以及当他们安装您的软件包或在终端(Bash、Zsh、Fish、PowerShell)中使用 typer 命令时,将自动提供自动完成功能。

有关更多功能和完整示例,请参阅教程 - 用户指南

依赖关系

Typer 借助了巨人的肩膀。它唯一的内部必需依赖是Click

默认情况下,它还包含额外的标准依赖项

  • rich:自动显示格式化的错误。
  • shellingham:在安装完成时自动检测当前 shell。
    • 使用 shellingham,您只需使用 --install-completion
    • 如果没有 shellingham,您必须传递要安装完成的 shell 名称,例如 --install-completion bash

typer-slim

如果您不想安装额外的标准可选依赖项,请安装 typer-slim

当您使用

pip install typer

...它包括与

pip install "typer-slim[standard]"

相同的代码和依赖项

注意typer 命令仅包含在 typer 软件包中。

许可协议

本项目采用 MIT 许可协议。

项目详情


下载文件

下载适用于您的平台的文件。如果您不确定选择哪个,请了解更多关于 安装软件包 的信息。

源分布

typer_slim-0.12.5.tar.gz (99.0 kB 查看哈希值)

上传时间

构建分布

typer_slim-0.12.5-py3-none-any.whl (47.1 kB 查看哈希值)

上传时间 Python 3

由以下支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面