コンテンツにスキップ

プロンプトで質問する

ユーザーに対話的に情報を尋ねる必要がある場合は、通常、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