小编典典

APT 命令行界面,类似于是/否输入?

all

有没有什么捷径可以实现 APT( 高级包工具 )命令行界面在 Python 中的功能?

我的意思是,当包管理器提示是/否问题后跟[Yes/no],脚本接受YES/Y/yes/yEnter(默认Yes为由大写字母暗示)。

input我在官方文档中找到的唯一内容是raw_input

我知道模仿并不难,但是重写很烦人:|


阅读 202

收藏
2022-07-04

共1个答案

小编典典

正如您所提到的,最简单的方法是使用raw_input()(或仅input()用于Python
3
)。没有内置的方法可以做到这一点。来自配方
577058

import sys


def query_yes_no(question, default="yes"):
    """Ask a yes/no question via raw_input() and return their answer.

    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
            It must be "yes" (the default), "no" or None (meaning
            an answer is required of the user).

    The "answer" return value is True for "yes" or False for "no".
    """
    valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
    if default is None:
        prompt = " [y/n] "
    elif default == "yes":
        prompt = " [Y/n] "
    elif default == "no":
        prompt = " [y/N] "
    else:
        raise ValueError("invalid default answer: '%s'" % default)

    while True:
        sys.stdout.write(question + prompt)
        choice = input().lower()
        if default is not None and choice == "":
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")

(对于 Python 2,使用raw_input代替input。) 用法示例:

>>> query_yes_no("Is cabbage yummier than cauliflower?")
Is cabbage yummier than cauliflower? [Y/n] oops
Please respond with 'yes' or 'no' (or 'y' or 'n').
Is cabbage yummier than cauliflower? [Y/n] [ENTER]
>>> True

>>> query_yes_no("Is cabbage yummier than cauliflower?", None)
Is cabbage yummier than cauliflower? [y/n] [ENTER]
Please respond with 'yes' or 'no' (or 'y' or 'n').
Is cabbage yummier than cauliflower? [y/n] y
>>> True
2022-07-04