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

新手上路,请多包涵

有没有什么捷径可以实现 APT( Advanced Package Tool )命令行界面在 Python 中的功能?

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

我在官方文档中找到的唯一东西是 inputraw_input

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

原文由 h3. 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 294
2 个回答

正如您所提到的,最简单的方法是使用 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

原文由 fmark 发布,翻译遵循 CC BY-SA 4.0 许可协议

我会这样做:

 # 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'")

原文由 Vicki Laidler 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题