添加 Typer
我们将从核心思想开始。
在另一个内部添加一个 typer.Typer()
应用程序。
管理项目¶
假设您正在创建一个CLI 程序来管理某个遥远地方的项目。
它可能在 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()
您将像这样使用它
$ python items.py create Wand
Creating item: Wand
管理用户¶
但随后您意识到,您还需要从CLI 应用程序中管理用户。
它可能是一个名为 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()
您将像这样使用它
$ python users.py create Camila
Creating user: Camila
将它们组合在一起¶
这两个部分非常相似。实际上,items.py
和 users.py
都包含 create
和 delete
命令。
但我们需要将它们作为同一个CLI 程序的一部分。
在这种情况下,就像 git remote
一样,我们可以将它们作为子命令放在另一个 typer.Typer()
CLI 程序中。
现在创建一个名为 main.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()
以下是我们在 main.py
中所做的操作:
- 导入其他 Python 模块(文件
users.py
和items.py
)。 - 创建主
typer.Typer()
应用程序。 - 使用
app.add_typer()
包含来自items.py
和users.py
的app
,这两个app
也是使用typer.Typer()
创建的。 - 定义一个
name
,用于表示每个“子 Typer”的命令,以将其自己的命令分组。
现在,您的CLI 程序具有 2 个命令:
users
:包含来自users.py
的app
中的所有命令(子命令)。items
:包含来自items.py
的app
中的所有命令(子命令)。
检查一下
// Check the help
$ 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:
items
users
现在,您拥有一个具有 items
和 users
命令的CLI 程序,它们又拥有自己的命令(子命令)。
让我们检查一下 items
命令
// Check the help for items
$ python main.py items --help
// It shows its own commands (subcommands): create, delete, sell
Usage: main.py items [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
create
delete
sell
// Try it
$ python main.py items create Wand
Creating item: Wand
$ python main.py items sell Vase
Selling item: Vase
提示
请注意,我们仍然在调用 $ python main.py
,但现在我们使用的是 items
命令。
现在检查一下 users
命令及其所有子命令
$ python main.py users --help
Usage: main.py users [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
create
delete
// Try it
$ python main.py users create Camila
Creating user: Camila
回顾¶
这就是核心思想。
您可以创建 typer.Typer()
应用程序,并将它们相互添加。
您可以根据需要创建任意级别的命令。
您需要子子子子命令吗?继续,创建所有需要的 typer.Typer()
,并使用 app.add_typer()
将它们组合在一起。
在接下来的部分中,我们将使用更多功能更新它,但您已经了解了核心思想。
这样,与 Click 类似,Typer 应用程序是可组合的,每个 typer.Typer()
都可以作为一个独立的CLI 应用程序,但也可以作为命令组添加到另一个 Typer 应用程序中。