类似APT命令行界面的确认输入?

211 投票
22 回答
258177 浏览
提问于 2025-04-15 23:58

有没有什么简单的方法可以在Python中实现APT(高级包管理工具)命令行界面所做的事情?

我的意思是,当包管理器问你一个是/否的问题,并且后面跟着[Yes/no]时,脚本可以接受YES/Y/yes/y或者直接按Enter(默认选择Yes,因为大写字母提示了这一点)。

我在官方文档中只找到inputraw_input这两个函数……

我知道模拟这个功能并不难,但每次都要重新写代码真的很烦人 :|

22 个回答

95

你可以使用 click 里的 confirm 方法。

import click

if click.confirm('Do you want to continue?', default=True):
    print('Do something')

这段代码会输出:

$ Do you want to continue? [Y/n]:

这个方法在 Python 2/3 上都能用,适用于 Linux、Mac 或 Windows 系统。

文档链接: http://click.pocoo.org/5/prompts/#confirmation-prompts

100

我会这样做:

# raw_input returns the empty string for "enter"
yes = {'yes','y', 'ye', ''}
no = {'no','n'}

choice = raw_input().lower()
if choice in yes:
   return True
elif choice in no:
   return False
else:
   sys.stdout.write("Please respond with 'yes' or 'no'")
280

正如你提到的,最简单的方法是使用 raw_input()(在 Python 3 中可以直接用 input())。其实没有其他内置的方法可以做到这一点。来自 Recipe 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

撰写回答