예 / 아니요 입력과 같은 APT 명령 행 인터페이스?


169

파이썬에서 APT ( Advanced Package Tool ) 명령 행 인터페이스의 기능을 수행 할 수있는 짧은 방법이 있습니까?

패키지 관리자가 예 / 아니오 질문 다음에을 묻는 메시지를 표시 [Yes/no]하면 스크립트에서 YES/Y/yes/y또는 Enter(기본값 Yes은 대문자로 표시됨) 을 수락 한다는 의미 입니다.

나는 공식 문서에서 찾을 수있는 유일한 방법입니다 inputraw_input...

나는 모방하기가 어렵지 않다는 것을 알고 있지만 다시 작성하는 것은 성가신 일입니다. |


15
파이썬 3에서는 raw_input()입니다 input().
Tobu

답변:


222

당신이 언급 한 바와 같이, 가장 쉬운 방법은 사용하는 것입니다 raw_input()(또는 단순히 input()위한 파이썬 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:그리고 아마도 부울을 반환 할 것입니다.
Ignacio Vazquez-Abrams 1

좋은 선택 Ignacio, 개정
fmark

24
실제로, 표준 라이브러리에는 strtobool 함수가 있습니다 : docs.python.org/2/distutils/…
Alexander Artemenko

14
그냥 기억 : raw_input()라고 input()Python3에
nachouve

정말 도움이되었습니다! 그냥 교체 raw_input()input()Python3합니다.
Muhammad Haseeb

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

strtobool파이썬의 표준 라이브러리 에는 다음과 같은 함수 가 있습니다 : http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool

이를 사용하여 사용자 입력을 확인하고 값 True또는 False값으로 변환 할 수 있습니다.


f아마 False의 약자 False == 0이므로 논리를 얻습니다. 함수가 int대신 a를 반환하는 이유는 bool나에게 신비입니다.
François Leblanc

데이터베이스에서 가장 일반적인 이유는 @ FrançoisLeblanc입니다. 명시 적으로 False또는 0(영) 이 아닌 경우 . bool 함수를 사용하여 평가 된 것은 true가되고 다음을 리턴 1합니다.
JayRizzo

@JayRizzo 나는 그것을 얻었고, 둘 다 기능면 에서 대부분 비슷 합니다. 그러나 싱글 톤 비교를 사용할 수 없다는 것을 의미합니다 if strtobool(string) is False: do_stuff().
François Leblanc

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)

이 파이썬이 작동하지 않습니다는 - raw_input이름이 바뀌 었습니다 input파이썬 3 stackoverflow.com/questions/21122540/...
브라이언 설렘을

9

prompter를 사용할 수도 있습니다 .

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

python 2/3 호환 더 많은 pythonic으로 fmark의 답변을 수정했습니다.

더 많은 오류 처리에 관심이 있다면 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과 호환되며 매우 읽기 쉽습니다. 나는이 대답을 사용했다.
François Leblanc

4

2.7에서, 이것은 비파이 토닉입니까?

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

적어도 예의 변형을 포착합니다.


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

나는 당신에게 @wsm을 편집했습니다. 그것을 검토하십시오 :-)
Gormador

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가 발생합니다.

파이썬 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

프로그래밍 멍청한 놈으로, 위의 답변이 지나치게 복잡하다는 것을 알았습니다. 특히 목표가 다양한 예 / 아니오 질문을 전달할 수있는 간단한 기능을 사용하여 사용자가 예 또는 아니오를 선택하도록 강요하는 경우 특히 그렇습니다. 이 페이지와 다른 여러 페이지를 and이 뒤져서 여러 가지 좋은 아이디어를 모두 빌린 후 다음과 같이 결론을 맺었습니다.

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

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()
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.