APT命令行界面一样的是/否输入?


169

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

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

我在官方文档中发现的唯一内容是inputand raw_input...

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


15
在Python 3中,raw_input()称为input()
东武

Answers:


222

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

用法示例:

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

elif choice in valid:我可能会返回一个布尔值。
伊格纳西奥·巴斯克斯

很好的选择,伊格纳西奥,修正
fmark

24
其实,有在非标准库中的函数strtobool:docs.python.org/2/distutils/...
亚历山大Artemenko

14
请记住: 在Python3中raw_input()被称为input()
nachouve '16

确实超级有帮助!只需更换raw_input()input()的Python3。
穆罕默德·哈西卜

93

我会这样:

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

8
raw_input()input()在Python3中被称为
gizzmole,

49

strtoboolPython的标准库中有一个函数:http : //docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool

您可以使用它来检查用户的输入并将其转换为TrueFalse值。


f可能代表False和False == 0,所以我明白了。但是,为什么函数返回a int而不是a bool仍然是一个谜。
弗朗索瓦·勒布朗

@FrançoisLeblanc关于为什么它在数据库中最常见。如果不是显式False0(零)。使用bool函数评估的所有其他内容都将变为true,并将返回:1
JayRizzo

@JayRizzo我明白了,它们在大多数方面都在功能上相似。但这意味着您不能使用单例比较,即if strtobool(string) is False: do_stuff()
弗朗索瓦·勒布朗

48

单个选择的一种非常简单(但不是非常复杂)的方法是:

msg = 'Shall I?'
shall = input("%s (y/N) " % msg).lower() == 'y'

您还可以围绕此编写一个简单的(略有改进)功能:

def yn_choice(message, default='y'):
    choices = 'Y/n' if default.lower() in ('y', 'yes') else 'y/N'
    choice = input("%s (%s) " % (message, choices))
    values = ('y', 'yes', '') if choices == 'Y/n' else ('y', 'yes')
    return choice.strip().lower() in values

注意:在Python 2上,请使用raw_input代替input


7
爱第一种方法。简短易行。我使用过类似的方法result = raw_input("message").lower() in ('y','yes')
Adrian Shum


24

如@Alexander Artemenko所述,这是使用strtobool的简单解决方案

from distutils.util import strtobool

def user_yes_no_query(question):
    sys.stdout.write('%s [y/n]\n' % question)
    while True:
        try:
            return strtobool(raw_input().lower())
        except ValueError:
            sys.stdout.write('Please respond with \'y\' or \'n\'.\n')

#usage

>>> user_yes_no_query('Do you like cheese?')
Do you like cheese? [y/n]
Only on tuesdays
Please respond with 'y' or 'n'.
ok
Please respond with 'y' or 'n'.
y
>>> True

8
只是好奇...为什么sys.stdout.write而不是print呢?
Anentropic

2
请注意,strtobool()(根据我的测试)不需要lower()。但是,这在其文档中并不明确。
Michael-Clay Shirky在哪里,

15

我知道已经以多种方式回答了这个问题,但这可能无法回答OP的特定问题(带有条件列表),但这是我针对最常见的用例所做的事情,并且比其他回答要简单得多:

answer = input('Please indicate approval: [y/n]')
if not answer or answer[0].lower() != 'y':
    print('You did not indicate approval')
    exit(1)

这并不与Python 2的工作- raw_input改名input在Python 3 stackoverflow.com/questions/21122540/...
布莱恩发麻

9

您也可以使用提示器

从README中无耻地摘录:

#pip install prompter

from prompter import yesno

>>> yesno('Really?')
Really? [Y/n]
True

>>> yesno('Really?')
Really? [Y/n] no
False

>>> yesno('Really?', default='no')
Really? [y/N]
True

4
当使用“ default ='no'”时,提示器的行为会倒退。选择“否”时将返回True,选择“是”时将返回False。
rem

7

我修改了fmark对python 2/3兼容更多pythonic的回答。

如果您对更多错误处理感兴趣,请参阅ipython的实用程序模块。

# PY2/3 compatibility
from __future__ import print_function
# You could use the six package for this
try:
    input_ = raw_input
except NameError:
    input_ = input

def query_yes_no(question, default=True):
    """Ask a yes/no question via standard input and return the answer.

    If invalid input is given, the user will be asked until
    they acutally give valid input.

    Args:
        question(str):
            A question that is presented to the user.
        default(bool|None):
            The default value when enter is pressed with no value.
            When None, there is no default value and the query
            will loop.
    Returns:
        A bool indicating whether user has entered yes or no.

    Side Effects:
        Blocks program execution until valid input(y/n) is given.
    """
    yes_list = ["yes", "y"]
    no_list = ["no", "n"]

    default_dict = {  # default => prompt default string
        None: "[y/n]",
        True: "[Y/n]",
        False: "[y/N]",
    }

    default_str = default_dict[default]
    prompt_str = "%s %s " % (question, default_str)

    while True:
        choice = input_(prompt_str).lower()

        if not choice and default is not None:
            return default
        if choice in yes_list:
            return True
        if choice in no_list:
            return False

        notification_str = "Please respond with 'y' or 'n'"
        print(notification_str)

与Python 2和3兼容,可读性强。我最终使用了这个答案。
弗朗索瓦·勒布朗

4

在2.7上,这是否非Pythonic?

if raw_input('your prompt').lower()[0]=='y':
   your code here
else:
   alternate code here

它至少捕获了Yes的任何变体。


4

使用raw_input()不存在的python 3.x进行相同的操作:

def ask(question, default = None):
    hasDefault = default is not None
    prompt = (question 
               + " [" + ["y", "Y"][hasDefault and default] + "/" 
               + ["n", "N"][hasDefault and not default] + "] ")

    while True:
        sys.stdout.write(prompt)
        choice = input().strip().lower()
        if choice == '':
            if default is not None:
                return default
        else:
            if "yes".startswith(choice):
                return True
            if "no".startswith(choice):
                return False

        sys.stdout.write("Please respond with 'yes' or 'no' "
                             "(or 'y' or 'n').\n")

不,这不起作用。实际上以多种方式。目前正在尝试对其进行修复,但是我认为这与完成后的接受答案非常相似。
Gormador

我编辑了您anwser @pjm。请考虑对其进行审核:-)
Gormador '16

3

对于Python 3,我正在使用以下功能:

def user_prompt(question: str) -> bool:
    """ Prompt the yes/no-*question* to the user. """
    from distutils.util import strtobool

    while True:
        user_input = input(question + " [y/n]: ").lower()
        try:
            result = strtobool(user_input)
            return result
        except ValueError:
            print("Please use y/n or yes/no.\n")

strtobool功能将字符串转换成一个布尔值。如果无法解析该字符串,则会引发ValueError。

在Python 3中,raw_input已重命名为input


2

您可以尝试使用类似下面的代码的方法,以便能够从此处显示的变量“ accepted”中进行选择:

print( 'accepted: {}'.format(accepted) )
# accepted: {'yes': ['', 'Yes', 'yes', 'YES', 'y', 'Y'], 'no': ['No', 'no', 'NO', 'n', 'N']}

这是代码..

#!/usr/bin/python3

def makeChoi(yeh, neh):
    accept = {}
    # for w in words:
    accept['yes'] = [ '', yeh, yeh.lower(), yeh.upper(), yeh.lower()[0], yeh.upper()[0] ]
    accept['no'] = [ neh, neh.lower(), neh.upper(), neh.lower()[0], neh.upper()[0] ]
    return accept

accepted = makeChoi('Yes', 'No')

def doYeh():
    print('Yeh! Let\'s do it.')

def doNeh():
    print('Neh! Let\'s not do it.')

choi = None
while not choi:
    choi = input( 'Please choose: Y/n? ' )
    if choi in accepted['yes']:
        choi = True
        doYeh()
    elif choi in accepted['no']:
        choi = True
        doNeh()
    else:
        print('Your choice was "{}". Please use an accepted input value ..'.format(choi))
        print( accepted )
        choi = None

2

作为编程新手,我发现上述答案过于复杂,特别是如果目标是要具有一个简单的功能,可以将各种“是/否”问题传递给用户,迫使用户选择“是”或“否”时,尤其如此。仔细浏览此页面和其他页面,并借鉴了所有各种好主意之后,我得出以下结论:

def yes_no(question_to_be_answered):
    while True:
        choice = input(question_to_be_answered).lower()
        if choice[:1] == 'y': 
            return True
        elif choice[:1] == 'n':
            return False
        else:
            print("Please respond with 'Yes' or 'No'\n")

#See it in Practice below 

musical_taste = yes_no('Do you like Pine Coladas?')
if musical_taste == True:
    print('and getting caught in the rain')
elif musical_taste == False:
    print('You clearly have no taste in music')

1
争论不应该被称为“问题”而不是“答案”吗?
AFP_555 '18 -10-28

1

这个怎么样:

def yes(prompt = 'Please enter Yes/No: '):
while True:
    try:
        i = raw_input(prompt)
    except KeyboardInterrupt:
        return False
    if i.lower() in ('yes','y'): return True
    elif i.lower() in ('no','n'): return False

1

这是我用的:

import sys

# cs = case sensitive
# ys = whatever you want to be "yes" - string or tuple of strings

#  prompt('promptString') == 1:               # only y
#  prompt('promptString',cs = 0) == 1:        # y or Y
#  prompt('promptString','Yes') == 1:         # only Yes
#  prompt('promptString',('y','yes')) == 1:   # only y or yes
#  prompt('promptString',('Y','Yes')) == 1:   # only Y or Yes
#  prompt('promptString',('y','yes'),0) == 1: # Yes, YES, yes, y, Y etc.

def prompt(ps,ys='y',cs=1):
    sys.stdout.write(ps)
    ii = raw_input()
    if cs == 0:
        ii = ii.lower()
    if type(ys) == tuple:
        for accept in ys:
            if cs == 0:
                accept = accept.lower()
            if ii == accept:
                return True
    else:
        if ii == ys:
            return True
    return False

1
def question(question, answers):
    acceptable = False
    while not acceptable:
        print(question + "specify '%s' or '%s'") % answers
        answer = raw_input()
        if answer.lower() == answers[0].lower() or answers[0].lower():
            print('Answer == %s') % answer
            acceptable = True
    return answer

raining = question("Is it raining today?", ("Y", "N"))

这就是我要做的。

输出量

Is it raining today? Specify 'Y' or 'N'
> Y
answer = 'Y'

1

这是我的看法,如果用户未确认操作,我只是想中止。

import distutils

if unsafe_case:
    print('Proceed with potentially unsafe thing? [y/n]')
    while True:
        try:
            verify = distutils.util.strtobool(raw_input())
            if not verify:
                raise SystemExit  # Abort on user reject
            break
        except ValueError as err:
            print('Please enter \'yes\' or \'no\'')
            # Try again
    print('Continuing ...')
do_unsafe_thing()

0

清理过的Python 3示例:

# inputExample.py

def confirm_input(question, default="no"):
    """Ask a yes/no question 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", "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: '{}}'".format(default))

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

def main():

    if confirm_input("\nDo you want to continue? "):
        print("You said yes because the function equals true. Continuing.")
    else:
        print("Quitting because the function equals false.")

if __name__ == "__main__":
    main()
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.