fastapi/typer

GitHub: fastapi/typer

Typer 是一个基于 Python 类型提示的 CLI 应用构建库,帮助开发者以极少的代码快速创建功能完善的命令行工具。

Stars: 19579 | Forks: 916

Typer

Typer, build great CLIs. Easy to code. Based on Python type hints.

Test Publish Coverage Package version

**文档**: [https://typer.tiangolo.com](https://typer.tiangolo.com) **源代码**: [https://github.com/fastapi/typer](https://github.com/fastapi/typer) Typer 是一个用于构建 CLI 应用程序的库,用户会**乐于使用**,开发者也会**乐于创建**。它基于 Python 的类型提示。 它也是一个命令行工具,用于运行脚本,并自动将其转换为 CLI 应用程序。 主要特性包括: * **编写直观**: 出色的编辑器支持。处处都有 补全。减少调试时间。设计易于使用和学习。减少阅读文档的时间。 * **易于使用**: 对最终用户来说易于使用。自动生成帮助,并为所有 shell 提供自动补全。 * **代码简短**: 最小化代码重复。每个参数声明都能带来多项功能。减少 bug。 * **从简单开始**: 最简单的示例只需为你的应用添加 2 行代码:**1 行导入,1 行函数调用**。 * **可扩展壮大**: 随心所欲地增加复杂度,创建任意复杂的命令树和子命令组,并配置选项和参数。 * **运行脚本**: Typer 包含一个 `typer` 命令/程序,你可以用它来运行脚本,即使脚本内部没有使用 Typer,也能自动将其转换为 CLI。 ## CLI 界的 FastAPI **Typer** 是 [FastAPI](https://fastapi.tiangolo.com) 的小兄弟,它是 CLI 界的 FastAPI。 ## 安装 创建并激活一个 [虚拟环境](https://typer.tiangolo.com/virtual-environments/),然后安装 **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. ```
**注意**:如果你的应用只有一个命令,默认情况下在用法中会**省略**命令名:`python main.py Camila`。但是,当有多个命令时,你必须**显式包含命令名**:`python main.py hello Camila`。有关更多详细信息,请参阅 [单个或多个命令](https://typer.tiangolo.com/tutorial/commands/one-or-multiple/)。 ### 回顾 总之,你只需将参数(*CLI 参数*和 *CLI 选项*)的类型作为函数参数声明**一次**。 你使用标准的现代 Python 类型来完成这一点。 你不需要学习新的语法、某个特定库的方法或类等。 只需标准的 **Python**。 例如,对于一个 `int`: ``` total: int ``` 或者对于一个 `bool` 标志: ``` force: bool ``` 对于**文件**、**路径**、**枚举** (选项) 等也是如此。还有一些工具可用于创建**子命令组**、添加元数据、额外的**验证**等。 **你将获得**:出色的编辑器支持,包括无处不在的**自动补全**和**类型检查**。 **你的用户将获得**:自动生成的 **`--help`**,以及在他们安装你的包或使用 `typer` 命令时,在他们的终端(Bash、Zsh、Fish、PowerShell)中获得**自动补全**。 有关包含更多功能的更完整示例,请参阅 教程 - 用户指南。 ## 依赖项 **Typer** 仅需要少数几个依赖项(并且大多数都非常小): * [`rich`](https://rich.readthedocs.io/en/stable/index.html):用于自动显示格式精美的错误。 * [`shellingham`](https://github.com/sarugaku/shellingham):用于在安装补全时自动检测当前的 shell。 * [`annotated-doc`](https://github.com/fastapi/annotated-doc):用于从 Python 类型注解生成文档。 * [`colorama`](https://github.com/tartley/colorama)(仅限 Windows):用于在 Windows 上生成彩色终端文本。 ### Click 代码 Typer 过去也依赖于 [Click](https://click.palletsprojects.com/),这是一个流行的用于在 Python 中构建 CLI 的工具。 自 0.26.0 版本起,Typer 已经内置了 Click(在内部包含了 Click 的源代码,而不是将其作为第三方包安装),并统一了 Typer 和内部嵌入的 Click 源代码之间的代码交互,以便在未来更容易维护。 请注意,随着我们继续改进和扩展 Typer 的代码库,未来某些 Click 功能将不再可用。 ### `typer-slim` 以前有一个名为 `typer-slim` 的 Typer 精简版本,它不包含依赖项 `rich` 和 `shellingham`,也没有 `typer` 命令。 然而,自 0.22.0 版本起,我们已停止对此的支持,现在 `typer-slim` 只会直接安装(完整的) Typer。 如果你想在全局范围内禁用 Rich,你可以将环境变量 `TYPER_USE_RICH` 设置为 `False` 或 `0`。 ## 许可证 该项目基于 MIT 许可证条款授权。
标签:CLI, Python, SOC Prime, WiFi技术, 开发工具, 开发框架, 无后门, 逆向工具