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

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

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

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

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



답변

당신이 언급 한 바와 같이, 가장 쉬운 방법은 사용하는 것입니다 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


답변

나는 이렇게 할 것입니다 :

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


답변

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

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


답변

단일 선택을 위해이 작업을 수행하는 매우 간단하지만 (정교하지는 않은) 방법은 다음과 같습니다.

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.


답변

clickconfirm방법을 사용할 수 있습니다 .

import click

if click.confirm('Do you want to continue?', default=True):
    print('Do something')

인쇄됩니다 :

$ Do you want to continue? [Y/n]:

Python 2/3Linux, Mac 또는 Windows에서 작동합니다 .

문서 : http://click.pocoo.org/5/prompts/#confirmation-prompts


답변

@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


답변

나는 이것이 여러 가지 방법으로 답변되었으며 OP의 특정 질문 (기준 목록과 함께)에 대답하지 않을 수도 있지만 이것이 가장 일반적인 유스 케이스에 대해 한 일이며 다른 답변보다 훨씬 간단합니다.

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