跳至内容

密码 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

密码提示

在接收密码时,在大多数 shell 中,在键入密码时不显示任何内容是很常见的。

该程序仍会接收密码,但屏幕上不会显示任何内容,甚至不会显示****

你可以使用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