gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:24:56 25 4
gpt4 key购买 nike

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

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

我在官方文档中找到的唯一内容是 inputraw_input...

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

最佳答案

正如您所提到的,最简单的方法是使用 raw_input() (或者只是 input() 用于 Python 3 )。没有内置的方法可以做到这一点。来自 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

关于python - APT 命令行界面,类似于是/否输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3041986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com