typer
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTyper
Typer
Official Typer skill to write code with best practices, keeping up to date with new versions and features.
官方 Typer skill,用于按照最佳实践编写代码,同时跟进新版本与新功能。
Installing typer
安装 typer
In a virtual environment, (with pip) or (with uv). For your library/project, add to the dependencies in .
pip install typeruv pip install typertyperpyproject.tomlDo not install or , they are both deprecated and will now simply install .
typer-slimtyper-clityperTyper supports Python 3.10 and above.
在虚拟环境中,使用 pip 可执行 ,使用 uv 可执行 。对于你的库或项目,请将 添加到 的依赖项中。
pip install typeruv pip install typertyperpyproject.toml不要安装 或 ,它们均已弃用,现在只会安装 。
typer-slimtyper-clityperTyper 支持 Python 3.10 及以上版本。
Use an explicit Typer
app
Typer使用显式 Typer
app
TyperFor maximum generalizability, create an explicit Typer app and register subcommand(s), instead of using :
typer.runpython
import typer
app = typer.Typer()
@app.command()
def hello():
print(f"Hello World")
if __name__ == "__main__":
app()instead of:
python
undefined为了尽可能提高通用性,请创建显式 Typer app 并注册子命令,而不要使用 :
typer.runpython
import typer
app = typer.Typer()
@app.command()
def hello():
print(f"Hello World")
if __name__ == "__main__":
app()而不是:
python
undefinedDO NOT DO THIS: Not extensible. Use Typer() instead.
DO NOT DO THIS: Not extensible. Use Typer() instead.
import typer
def main():
print(f"Hello World")
if name == "main":
typer.run(main)
undefinedimport typer
def main():
print(f"Hello World")
if name == "main":
typer.run(main)
undefinedExecute the app
执行 app
To execute the app in the terminal, run
bash
python main.pyWhen multiple commands are registered to the Typer app, you have to add the command name:
bash
python main.py helloTo see the automatically generated help documentation, run
bash
python main.py --helpor set to when creating the add to automatically show the help when running a command without any arguments.
no_args_is_helpTrueTyper()若要在终端中执行该 app,请运行
bash
python main.py当 Typer app 中注册了多个命令时,必须添加命令名称:
bash
python main.py hello要查看自动生成的帮助文档,请运行
bash
python main.py --help也可以在创建 app 时将 设置为 ,以便在运行命令时未提供任何参数的情况下自动显示帮助信息。
Typer()no_args_is_helpTrueUse Annotated
Annotated使用 Annotated
AnnotatedAlways prefer the style for declarations of CLI arguments and options.
AnnotatedIt allows us to pass additional metadata that can be used by Typer.
python
from typing import Annotated
import typer
app = typer.Typer()
@app.command()
def hello(name: Annotated[str, typer.Argument()] = "World"):
# Note that name is an optional Argument, as a default is provided
print(f"Hello {name}")
if __name__ == "__main__":
app()This program can be run as-is, or can provide a specific name:
bash
python main.py
python main.py RickAn older way of setting a default value is this:
python
undefined声明 CLI 参数和选项时,始终优先使用 风格。
Annotated它允许传递 Typer 可用的其他元数据。
python
from typing import Annotated
import typer
app = typer.Typer()
@app.command()
def hello(name: Annotated[str, typer.Argument()] = "World"):
# Note that name is an optional Argument, as a default is provided
print(f"Hello {name}")
if __name__ == "__main__":
app()该程序可以直接运行,也可以提供指定名称:
bash
python main.py
python main.py Rick设置默认值的旧式写法如下:
python
undefinedDO NOT DO THIS: old style. Use Annotated instead.
DO NOT DO THIS: old style. Use Annotated instead.
@app.command()
def main(name: str = typer.Argument(default="World")):
# Note that name is an optional Argument, as a default is provided
print(f"Hello {name}")
Similarly, the old style could use ellipsis (...) to explicitly mark an argument as required.
```python@app.command()
def main(name: str = typer.Argument(default="World")):
# Note that name is an optional Argument, as a default is provided
print(f"Hello {name}")
类似地,旧式写法还可以使用省略号 (...) 明确将参数标记为必填项。
```pythonDO NOT DO THIS: old style. Use Annotated without a default value instead.
DO NOT DO THIS: old style. Use Annotated without a default value instead.
@app.command()
def main(name: str = typer.Argument(default=...)):
# Note that name is now a required Argument
print(f"Hello {name}")
undefined@app.command()
def main(name: str = typer.Argument(default=...)):
# Note that name is now a required Argument
print(f"Hello {name}")
undefinedCLI Options
CLI 选项
CLI options are declared in a similar fashion as arguments, but will be called on the CLI with a single dash (single letter) or 2 dashes (full name).
The CLI option name is automatically generated from the variable name, so becomes automatically:
user_name--user-namepython
from typing import Annotated
import typer
app = typer.Typer()
@app.command()
def main(user_name: Annotated[str, typer.Option()]):
# On the CLI, the required user name can be specified with --user-name
print(f"Hello {user_name}")
if __name__ == "__main__":
app()If you want to specify a different name, or want to add a short version, declare them in the :
typer.Optionpython
from typing import Annotated
import typer
app = typer.Typer()
@app.command()
def main(user_name: Annotated[str, typer.Option("--name", "-n")]):
# On the CLI, the required user name can be specified with -n or --name
print(f"Hello {user_name}")
if __name__ == "__main__":
app()You can run this program as such:
bash
python main.py -n "Rick"
python main.py --name "Morty"CLI 选项的声明方式与参数类似,但在 CLI 中调用时使用单个短横线(单字母)或两个短横线(完整名称)。
CLI 选项名称会根据变量名自动生成,因此 会自动变为 :
user_name--user-namepython
from typing import Annotated
import typer
app = typer.Typer()
@app.command()
def main(user_name: Annotated[str, typer.Option()]):
# On the CLI, the required user name can be specified with --user-name
print(f"Hello {user_name}")
if __name__ == "__main__":
app()如果希望指定其他名称或添加短版本,可在 中声明:
typer.Optionpython
from typing import Annotated
import typer
app = typer.Typer()
@app.command()
def main(user_name: Annotated[str, typer.Option("--name", "-n")]):
# On the CLI, the required user name can be specified with -n or --name
print(f"Hello {user_name}")
if __name__ == "__main__":
app()可以按如下方式运行此程序:
bash
python main.py -n "Rick"
python main.py --name "Morty"CLI options with multiple values
包含多个值的 CLI 选项
By declaring a CLI option as a list, it can receive multiple values:
python
from typing import Annotated
import typer
app = typer.Typer()
@app.command()
def main(user: Annotated[list[str] | None, typer.Option()] = None):
if not user:
print(f"No users provided!")
raise typer.Abort()
for u in user:
print(f"Processing user: {u}")
if __name__ == "__main__":
app()This can be executed like so:
bash
python main.py --user Rick --user Morty --user Summer将 CLI 选项声明为列表后,它可以接收多个值:
python
from typing import Annotated
import typer
app = typer.Typer()
@app.command()
def main(user: Annotated[list[str] | None, typer.Option()] = None):
if not user:
print(f"No users provided!")
raise typer.Abort()
for u in user:
print(f"Processing user: {u}")
if __name__ == "__main__":
app()可按如下方式执行:
bash
python main.py --user Rick --user Morty --user SummerRich
Rich
By default, Rich can be used with its custom markup syntax to set colors and styles, e.g.
python
from rich import print
print("[bold red]Alert![/bold red] [green]Portal gun[/green] shooting! :boom:")Typer supports using Rich formatting in the docstrings and the help messages of CLI arguments and CLI options.
python
from typing import Annotated
import typer
app = typer.Typer(rich_markup_mode="rich")
@app.command()
def create(
username: Annotated[
str, typer.Argument(help="The username to be [green]created[/green]")
],
):
"""
[bold green]Create[/bold green] a new [italic]shiny[/italic] user. :sparkles:
This requires a [underline]username[/underline].
"""
print(f"Creating user: {username}")
@app.command(help="[bold red]Delete[/bold red] a user with [italic]username[/italic].")
def delete(
username: Annotated[
str, typer.Argument(help="The username to be [red]deleted[/red]")
],
):
"""
Some internal utility function to delete.
"""
print(f"Deleting user: {username}")
if __name__ == "__main__":
app()To disable Rich formatting, set to when creating a app. By default (when no value is given), Rich formatting is enabled.
rich_markup_modeNoneTyper()默认情况下,可以使用 Rich 及其自定义标记语法来设置颜色和样式,例如:
python
from rich import print
print("[bold red]Alert![/bold red] [green]Portal gun[/green] shooting! :boom:")Typer 支持在 CLI 参数和 CLI 选项的文档字符串及帮助消息中使用 Rich 格式。
python
from typing import Annotated
import typer
app = typer.Typer(rich_markup_mode="rich")
@app.command()
def create(
username: Annotated[
str, typer.Argument(help="The username to be [green]created[/green]")
],
):
"""
[bold green]Create[/bold green] a new [italic]shiny[/italic] user. :sparkles:
This requires a [underline]username[/underline].
"""
print(f"Creating user: {username}")
@app.command(help="[bold red]Delete[/bold red] a user with [italic]username[/italic].")
def delete(
username: Annotated[
str, typer.Argument(help="The username to be [red]deleted[/red]")
],
):
"""
Some internal utility function to delete.
"""
print(f"Deleting user: {username}")
if __name__ == "__main__":
app()若要禁用 Rich 格式化,请在创建 app 时将 设置为 。默认情况下(未指定值时),Rich 格式化处于启用状态。
Typer()rich_markup_modeNoneRich markdown
Rich Markdown
You can also set to to use Markdown in the docstring:
rich_markup_mode"markdown"python
from typing import Annotated
import typer
app = typer.Typer(rich_markup_mode="markdown")
@app.command(help="**Delete** a user with *username*.")
def delete(
username: Annotated[
str, typer.Argument(help="The username to be **deleted** :boom:")
],
):
print(f"Deleting user: {username}")
if __name__ == "__main__":
app()你也可以将 设置为 ,以在文档字符串中使用 Markdown:
rich_markup_mode"markdown"python
from typing import Annotated
import typer
app = typer.Typer(rich_markup_mode="markdown")
@app.command(help="**Delete** a user with *username*.")
def delete(
username: Annotated[
str, typer.Argument(help="The username to be **deleted** :boom:")
],
):
print(f"Deleting user: {username}")
if __name__ == "__main__":
app()Click
Click
Originally, Typer was built on Click. However, since version 0.26.0, Typer has vendored Click. As such, Click extensions should not be used anymore.
Other settings of and that came from Click but shouldn't be used in Typer anymore, include: , , , , , , and .
OptionArgumentexpose_valueshell_completeshow_choiceserrorsprompt_requiredis_flagflag_valueallow_from_autoenvCode bases using these should be refactored to use pure Typer functionality.
Typer 最初构建于 Click 之上。然而,从 0.26.0 版本开始,Typer 已内置 Click。因此,不应再使用 Click 扩展。
源自 Click、但不应再在 Typer 中使用的 和 其他设置包括:、、、、、、 和 。
OptionArgumentexpose_valueshell_completeshow_choiceserrorsprompt_requiredis_flagflag_valueallow_from_autoenv使用这些设置的代码库应重构为使用纯 Typer 功能。