コンテンツへスキップ

パスワードCLIオプションと確認プロンプト

プロンプトを表示する以外にも、CLIオプションconfirmation_prompt=Trueを設定できます。

import typer
from typing_extensions import Annotated


def main(
    name: str,
    email: Annotated[str, typer.Option(prompt=True, confirmation_prompt=True)],
):
    print(f"Hello {name}, your email is {email}")


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

ヒント

可能であれば、Annotatedバージョンを使用することをお勧めします。

import typer


def main(
    name: str, email: str = typer.Option(..., prompt=True, confirmation_prompt=True)
):
    print(f"Hello {name}, your email is {email}")


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

そして、CLIプログラムは確認を求めます。

$ python main.py Camila

// It prompts for the email
# Email: $ camila@example.com
# Repeat for confirmation: $ camila@example.com

Hello Camila, your email is camila@example.com

パスワードプロンプト

パスワードを受け取る際、(ほとんどのシェルでは)パスワード入力中に画面に何も表示されないのが一般的です。

プログラムはパスワードを受け取りますが、画面には何も表示されません。****も表示されません。

hide_input=Trueを使用して同じことができます。

そして、これをconfirmation_prompt=Trueと組み合わせることで、簡単にパスワードの二重確認を行うことができます。

import typer
from typing_extensions import Annotated


def main(
    name: str,
    password: Annotated[
        str, typer.Option(prompt=True, confirmation_prompt=True, hide_input=True)
    ],
):
    print(f"Hello {name}. Doing something very secure with password.")
    print(f"...just kidding, here it is, very insecure: {password}")


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

ヒント

可能であれば、Annotatedバージョンを使用することをお勧めします。

import typer


def main(
    name: str,
    password: str = typer.Option(
        ..., prompt=True, confirmation_prompt=True, hide_input=True
    ),
):
    print(f"Hello {name}. Doing something very secure with password.")
    print(f"...just kidding, here it is, very insecure: {password}")


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

確認してください

$ python main.py Camila

// It prompts for the password, but doesn't show anything when you type
# Password: $
# Repeat for confirmation: $

// Let's imagine the password typed was "typerrocks"
Hello Camila. Doing something very secure with password.
...just kidding, here it is, very insecure: typerrocks