跳到主要内容

其他小功能

交互式 prompt

typer.prompt

使用 typer.prompt 以交互式方法输入参数

if you absolutely need to ask for interactive information without using a CLI option, you can use 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)

image-20240801141645016

typer.confirm

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)
image-20240801141726957

As it's very common to abort if the user doesn't confirm, there's an integrated parameter abort that does it automatically

也就是自动 raise typer.Abort()

delete = typer.confirm("Are you sure you want to delete it?", abort=True)

image-20240801142037489

使用 Rich 的 prompt

import typer
from rich.prompt import Prompt


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


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

image-20240801142339079