source

APT 명령줄 인터페이스와 같은 예/아니오 입력?

itover 2022. 11. 22. 21:29
반응형

APT 명령줄 인터페이스와 같은 예/아니오 입력?

APT(Advanced Package Tool) 명령줄 인터페이스가 Python에서 하는 것을 실현하기 위한 간단한 방법이 있습니까?

패키지 매니저가 예/아니오 질문을 하면[Yes/no], 스크립트는YES/Y/yes/y또는 (에 준함)Yes대문자로 암시한 바와 같이.

공식 문서에서 찾은 건input그리고.raw_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

난 이렇게 할 거야:

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

클릭을 사용할 수 있습니다.confirm방법.

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/ #information-disclosing

기능이 있습니다.strtoboolPython 표준 라이브러리: 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.

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

프롬프터를 사용할 수도 있습니다.

뻔뻔스럽게도 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

fmark의 답변을 python 2/3 호환성이 있는 python으로 수정했습니다.

오류 처리가 더 많은 항목에 관심이 있는 경우 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 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]: ")
        try:
            return bool(strtobool(user_input))
        except ValueError:
            print("Please use y/n or yes/no.\n")

이 함수는 문자열을 부울로 변환합니다.문자열을 구문 분석할 수 없는 경우 ValueError가 발생합니다.

Python 3의 경우raw_input()이름이 로 변경되었습니다.

Geoff가 말했듯이 strtobool은 실제로 0 또는 1을 반환하기 때문에 결과는 bool로 캐스팅되어야 합니다.


이것은, 의 실장입니다.strtobool를 ""로 true를 추가할 수

def strtobool (val):
    """Convert a string representation of truth to true (1) or false (0).
    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
    'val' is anything else.
    """
    val = val.lower()
    if val in ('y', 'yes', 't', 'true', 'on', '1'):
        return 1
    elif val in ('n', 'no', 'f', 'false', 'off', '0'):
        return 0
    else:
        raise ValueError("invalid truth value %r" % (val,))

2.7에서는 너무 비음향적인가요?

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

적어도 Yes의 모든 변형을 캡처합니다.

3.에 도 같은 .여기서 python 3.x 는 python 3.x 입니다.raw_input()존재하지 않습니다.

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

아래 코드와 같은 방법으로 '승인됨' 변수에서 선택할 수 있습니다.

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

프로그래밍 노브로서, 나는 위의 답변들이 지나치게 복잡하다는 것을 알았다.특히 다양한 예/아니오 질문을 주고받을 수 있는 단순한 기능을 가지고 있고, 사용자가 예/아니오를 선택하도록 하는 것이 목적이라면 말이다.이 페이지와 다른 여러 페이지를 훑어보고 여러 가지 좋은 아이디어를 빌린 결과, 다음과 같은 결과가 나왔습니다.

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

이거 어때:

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

사용하고 있는 것은 다음과 같습니다.

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

제 생각은 이렇습니다.저는 단순히 사용자가 액션을 긍정하지 않으면 중단하고 싶었습니다.

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

Python 3.8 이상 탑재된 원라이너:

while res:= input("When correct, press enter to continue...").lower() not in {'y','yes','Y','YES',''}: pass

파이썬 x.x

res = True
while res:
    res = input("Please confirm with y/yes...").lower(); res = res not in {'y','yes','Y','YES',''}

, 아니오의 에 다음 예에서는 첫 이 '예' 또는 '아니오'라는 입니다.while두은 '어울리다'를 사용하는 것입니다.recursion을 그 - 정의하다.

def yes_or_no(question):
    while "the answer is invalid":
        reply = str(input(question+' (y/n): ')).lower().strip()
        if reply[:1] == 'y':
            return True
        if reply[:1] == 'n':
            return False

yes_or_no("Do you know who Novak Djokovic is?")

두 번째 솔루션:

def yes_or_no(question):
    """Simple Yes/No Function."""
    prompt = f'{question} ? (y/n): '
    answer = input(prompt).strip().lower()
    if answer not in ['y', 'n']:
        print(f'{answer} is invalid, please try again...')
        return yes_or_no(question)
    if answer == 'y':
        return True
    return False

def main():
    """Run main function."""
    answer = yes_or_no("Do you know who Novak Djokovic is?")
    print(f'you answer was: {answer}')


if __name__ == '__main__':
    main()

제가 예전에 했던 일은...

question = 'Will the apple fall?'
print(question)
answer = int(input("Pls enter the answer: "
if answer == "y",
print('Well done')
print(answer)

언급URL : https://stackoverflow.com/questions/3041986/apt-command-line-interface-like-yes-no-input

반응형