跳至内容

使用提示询问

当您需要以交互方式向用户询问信息时,通常应该使用 CLI 选项带提示,因为它们允许以非交互方式使用 CLI 程序(例如,Bash 脚本可以使用它)。

但是,如果您绝对需要在不使用CLI 选项的情况下询问交互式信息,可以使用 typer.prompt()

import typer


def main():
    person_name = typer.prompt("What's your name?")
    print(f"Hello {person_name}")


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

检查它

$ python main.py

# What's your name?:$ Camila

Hello Camila

确认

还有一种询问确认的替代方法。同样,如果可能,您应该使用 CLI 选项带确认提示

import typer


def main():
    delete = typer.confirm("Are you sure you want to delete it?")
    if not delete:
        print("Not deleting")
        raise typer.Abort()
    print("Deleting it!")


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

检查它

$ python main.py

# Are you sure you want to delete it? [y/N]:$ y

Deleting it!

// This time cancel it
$ python main.py

# Are you sure you want to delete it? [y/N]:$ n

Not deleting
Aborted!

确认或中止

由于用户不确认就中止的情况非常常见,因此我们集成了一个名为abort的参数,可以自动执行此操作。

import typer


def main():
    delete = typer.confirm("Are you sure you want to delete it?", abort=True)
    print("Deleting it!")


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

# Are you sure you want to delete it? [y/N]:$ y

Deleting it!

// This time cancel it
$ python main.py

# Are you sure you want to delete it? [y/N]:$ n

Aborted!

使用 Rich 提示

如果您按照打印和颜色中的说明安装了 Rich,您可以使用 Rich 来提示用户输入。

import typer
from rich.prompt import Prompt


def main():
    name = Prompt.ask("Enter your name :sunglasses:")
    print(f"Hey there {name}!")


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

运行时,它将显示如下:

$ python main.py

# Enter your name 😎:$ Morty

Hello Morty