APT कमांड लाइन इंटरफ़ेस-जैसे हाँ / कोई इनपुट नहीं?


169

पायथन में एपीटी ( एडवांस्ड पैकेज टूल ) कमांड लाइन इंटरफेस क्या करता है, इसे प्राप्त करने का कोई छोटा तरीका है ?

मेरा मतलब है, जब पैकेज प्रबंधक एक हाँ / नहीं के बाद आने वाले प्रश्न का संकेत देता है [Yes/no], तो स्क्रिप्ट स्वीकार करती है YES/Y/yes/yया Enter( Yesकैपिटल लेटर द्वारा संकेत के अनुसार चूक )।

आधिकारिक डॉक्स में केवल एक चीज मुझे मिलती है inputऔर वह है raw_input...

मुझे पता है कि इसका अनुकरण करना कठिन नहीं है, लेकिन इसे फिर से लिखना कष्टप्रद है: |


15
पायथन 3 में, raw_input()कहा जाता है input()
तोबू

जवाबों:


222

आप उल्लेख किया है, सबसे आसान तरीका उपयोग करने के लिए है raw_input()(या बस input()के लिए अजगर 3 )। ऐसा करने का कोई अंतर्निहित तरीका नहीं है। से पकाने की विधि 577,058 :

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
वास्तव में, फ्रेड लाइब्रेरी में एक फंक्शन स्ट्रोबोबोल है: docs.python.org/2/distutils/…
अलेक्जेंडर

14
बस एक याद: पायथन 3 में raw_input()कहा जाता input()है
nachouve

वास्तव में सुपर सहायक! बस पायथन 3 के raw_input()साथ बदलें input()
मुहम्मद हसीब

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 == 0, इसलिए मुझे तर्क मिलता है। हालांकि फ़ंक्शन एक के intबजाय वापस आ जाएगा, boolहालांकि मेरे लिए एक रहस्य है।
फ़्राँस्वा लेब्लांक

@ क्यों यह डेटाबेस में सबसे आम है के रूप में FrançoisLeblanc। यदि यह स्पष्ट रूप से Falseया 0(शून्य) नहीं है। कुछ भी, जो बूल फ़ंक्शन का उपयोग करके मूल्यांकन किया जाता है, सच हो जाता है और वापस आ जाएगा 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

नोट: पर पायथन 2, का उपयोग raw_inputकरने के बजाय input


7
पहले दृष्टिकोण को प्यार करो। छोटा और आसान। मैंने कुछ का इस्तेमाल कियाresult = raw_input("message").lower() in ('y','yes')
एड्रियन शम

47

आप उपयोग कर सकते हैं क्लिक के 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/3लिनक्स, मैक या विंडोज पर काम करना चाहिए ।

डॉक्स: http://click.pocoo.org/5/prompts/#confirmation-prompts


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?
एंथ्रोपिक

2
ध्यान दें कि strtobool()(मेरे परीक्षणों से) की आवश्यकता नहीं है lower()। हालाँकि, इसके दस्तावेज़ीकरण में यह स्पष्ट नहीं है।
माइकल - जहां

15

मुझे पता है कि इस तरीके का एक गुच्छा उत्तर दिया गया है और यह ओपी के विशिष्ट प्रश्न (मानदंड की सूची के साथ) का जवाब नहीं दे सकता है, लेकिन यह मैंने सबसे सामान्य उपयोग के मामले के लिए किया है और यह अन्य प्रतिक्रियाओं की तुलना में कहीं अधिक सरल है:

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

यह अजगर 2 के साथ काम नहीं करता है - अजगर में 3 raw_inputनाम बदल दिया गया था stackoverflow.com/questions/21122540/…input
ब्रायन टिंगल

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
जब आप इसे "डिफ़ॉल्ट = 'नहीं' के साथ प्रयोग कर रहे हैं, तो प्रतिशोध का व्यवहार बहुत पीछे है; जब आप 'नहीं' चुनते हैं और 'हाँ' चुनते हैं तो यह गलत है कि यह वापस आ जाएगा।
रेम

7

मैंने अजगर के 2/3 संगत अधिक पायथोनिक द्वारा फार्क के उत्तर को संशोधित किया।

यदि आप अधिक त्रुटि से निपटने के साथ किसी चीज में रुचि रखते हैं तो 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)

पायथन 2 और 3 दोनों के साथ संगत, बहुत पठनीय। मैं इस जवाब का उपयोग कर समाप्त हुआ।
फ्रांस्वा लेब्लांक

4

2.7 पर, क्या यह बहुत अधिक गैर-पाइथोनिक है?

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

यह हाँ के किसी भी रूपांतर को कम से कम पकड़ लेता है।


4

अजगर 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")

नहीं, यह काम नहीं करता है। वास्तव में एक से अधिक तरीकों से। वर्तमान में इसे ठीक करने की कोशिश की जा रही है, लेकिन मुझे लगता है कि यह बहुत अच्छा लगेगा क्योंकि मैं कर रहा हूँ।
गोरमडोर

मैंने आपको awser @pjm संपादित किया है। कृपया इसकी समीक्षा करने पर विचार करें :-)
गोरमडोर

3

पायथन 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 समारोह एक bool में एक स्ट्रिंग बदल देता है। यदि स्ट्रिंग केंट को पार्स नहीं किया जाता है तो यह एक वैल्यूएयर बढ़ा देगा।

पायथन में 3 रॉ_इनपुट का नाम बदलकर इनपुट किया गया है ।


2

आप नीचे दिए गए कोड की तरह कुछ कोशिश कर सकते हैं, यहाँ '' स्वीकार किए गए '' शो के विकल्पों के साथ काम करने में सक्षम होने के लिए:

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

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

एक साफ पायथन 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()
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.