Interface de linha de comando do APT como entrada sim / não?


169

Existe alguma maneira curta de conseguir o que a interface da linha de comando do APT ( Advanced Package Tool ) faz no Python?

Quero dizer, quando o gerenciador de pacotes solicita uma pergunta de sim / não seguida por [Yes/no], o script aceita YES/Y/yes/you Enter(o padrão Yesé sugerido pela letra maiúscula).

A única coisa que encontro nos documentos oficiais é inpute raw_input...

Eu sei que não é tão difícil de emular, mas é irritante reescrever: |


15
No Python 3, raw_input()é chamado input().
Tobu

Respostas:


222

Como você mencionou, a maneira mais fácil é usar raw_input()(ou simplesmente input()para Python 3 ). Não há uma maneira integrada de fazer isso. Da receita 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")

Exemplo de uso:

>>> 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:E eu provavelmente retornaria um booleano.
Ignacio Vazquez-Abrams

Boa escolha Ignacio, alterando
fmark 15/06/10

24
Na verdade, há uma strtobool função na biblioteca do standart: docs.python.org/2/distutils/...
Alexander Artemenko

14
Lembre-se: raw_input()é chamado input()em Python3
nachouve

De fato super útil! Basta substituir raw_input()por input()para Python3.
Muhammad Haseeb

93

Eu faria assim:

# 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()é chamado input()em Python3
gizzmole 7/18

49

Há uma função strtoboolna biblioteca padrão do Python: http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool

Você pode usá-lo para verificar a entrada do usuário e transformá-lo em Trueou Falsevalor.


fprovavelmente significa False e False == 0, portanto, entendi a lógica. Por que a função retornaria um em intvez de a boolé um mistério para mim.
François Leblanc

@ FrançoisLeblanc sobre Por que é mais comum em bancos de dados. Se não for explicitamente Falseou 0(Zero). Qualquer coisa, outra coisa que é avaliada usando a função bool torna-se verdadeira e vai voltar: 1.
21419 JayRizzo

@ JayRizzo Eu entendo isso, e ambos são funcionalmente similares na maioria dos aspectos. Mas isso significa que você não pode usar comparação de singleton, ou seja if strtobool(string) is False: do_stuff().
François Leblanc

48

Uma maneira muito simples (mas não muito sofisticada) de fazer isso para uma única escolha seria:

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

Você também pode escrever uma função simples (um pouco aprimorada) em torno disso:

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

Nota: No Python 2, use em raw_inputvez de input.


7
Ame a primeira abordagem. Curto e fácil. Eu usei algo comoresult = raw_input("message").lower() in ('y','yes')
Adrian Shum 03/03


24

como mencionado por @Alexander Artemenko, aqui está uma solução simples usando o 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
apenas curioso ... por que em sys.stdout.writevez de print?
Anentropic

2
Observe que strtobool()(dos meus testes) não requer a lower(). Isso não está explícito em sua documentação, no entanto.
Michael - de onde Clay Shirky

15

Eu sei que isso foi respondido de várias maneiras e isso pode não responder à pergunta específica do OP (com a lista de critérios), mas foi o que fiz no caso de uso mais comum e é muito mais simples do que as outras respostas:

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

isso não funciona com o python 2 - raw_inputfoi renomeado inputno python 3 stackoverflow.com/questions/21122540/…
Brian Tingle 13/17

9

Você também pode usar o prompter .

Desavergonhadamente retirado do 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
Lembre-se de que o comportamento do prompter é bastante retroativo quando você o usa com "default = 'no'"; ele retornará True quando você escolher 'não' e False quando você escolher 'sim'.
rem

7

Eu modifiquei a resposta da fmark para por python 2/3 compatível com mais python.

Consulte o módulo utilitário do ipython se você estiver interessado em algo com mais manipulação de erros

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

Compatível com Python 2 e 3, muito legível. Acabei usando esta resposta.
François Leblanc

4

no 2.7, isso é não-pitônico demais?

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

captura qualquer variação de Sim pelo menos.


4

Fazendo o mesmo com o python 3.x, onde raw_input()não existe:

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

Não, isso não funciona. Em mais de uma maneira, na verdade. Atualmente estou tentando consertá-lo, mas acho que isso será parecido com a resposta aceita depois que eu terminar.
Gormador 4/11

Eu editei você anwser @pjm. Por favor, considere revê-lo :-)
Gormador

3

Para Python 3, estou usando esta função:

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

A função strtobool converte uma string em um bool. Se a string não puder ser analisada, ela gerará um ValueError.

No Python 3, raw_input foi renomeado para input .


2

Você pode tentar algo como o código abaixo para poder trabalhar com opções da variável 'aceito' exibida aqui:

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

Aqui está o código ..

#!/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

Como noob de programação, achei um monte de respostas acima muito complexas, especialmente se o objetivo é ter uma função simples para a qual você pode passar várias perguntas de sim / não, forçando o usuário a selecionar sim ou não. Depois de vasculhar esta página e várias outras e emprestar todas as várias boas idéias, acabei com o seguinte:

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
O argumento não deveria ser chamado de "pergunta" em vez de "resposta"?
AFP_555 28/10

1

Que tal agora:

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

Isto é o que eu uso:

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

É assim que eu faria.

Resultado

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

1

Aqui está minha opinião: eu simplesmente queria abortar se o usuário não afirmasse a ação.

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

Um exemplo limpo de 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()
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.