এপিটি কমান্ড লাইন ইন্টারফেসের মতো হ্যাঁ / কোনও ইনপুট নেই?


169

পাইথনে এপিটি ( অ্যাডভান্সড প্যাকেজ টুল ) কমান্ড লাইন ইন্টারফেসটি কী অর্জন করার কোনও সংক্ষিপ্ত উপায় আছে ?

আমি বলতে চাইছি, প্যাকেজ ম্যানেজার যখন হ্যাঁ / কোনও প্রশ্ন অনুসরণ করে না [Yes/no], তখন স্ক্রিপ্টটি গ্রহণ করে YES/Y/yes/yবা Enter(বড় Yesহাতের অক্ষর হিসাবে ডিফল্ট )।

সরকারী দস্তাবেজগুলিতে আমি যে জিনিসটি পাই তা হ'ল inputএবং raw_input...

আমি জানি এটি অনুকরণ করা খুব কঠিন নয়, তবে এটি আবার লিখতে বিরক্তিকর: |


15
পাইথন 3 raw_input()এ বলা হয় input()
তোবু

উত্তর:


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

ভাল পছন্দ Ignacio, সংশোধন
fmark

24
প্রকৃতপক্ষে, স্ট্যান্ডার্ড লাইব্রেরিতে একটি ফাংশন স্ট্র্টবুল রয়েছে: ডকস.পিথন.অর্গ
আলেকজান্ডার আর্টেমেনকো

14
কেবল একটি মনে রাখবেন: raw_input()input()
পাইথন 3

সত্যিই সুপার সহায়ক! শুধু প্রতিস্থাপন raw_input()সঙ্গে input()Python3 জন্য।
মুহাম্মাদ হাসিব

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()পাইথন 3
জিজমোল

49

strtoboolপাইথনের স্ট্যান্ডার্ড লাইব্রেরিতে একটি ফাংশন রয়েছে: http://docs.python.org/2/distutils/apiref.html?hightlight=distutils.util#distutils.util.strtobool

আপনি এটি ব্যবহারকারীর ইনপুট চেক করতে এবং এটির Trueবা Falseমানতে রূপান্তর করতে ব্যবহার করতে পারেন ।


fসম্ভবত মিথ্যা জন্য দাঁড়ানো, এবং False == 0, তাই আমি যুক্তি পেতে। কেন ফাংশনটি তার intপরিবর্তে ফিরে আসবে boolতা আমার কাছে রহস্য।
ফ্রেঞ্চোইস লেব্ল্যাঙ্ক

ডেটাবেসগুলিতে কেন এটি সবচেয়ে বেশি দেখা যায় তা সম্পর্কে @ ফ্রানয়েইসলেব্ল্যাঙ্ক। যদি এটি স্পষ্টভাবে Falseবা 0(জিরো) না হয়। যেকোনো কিছু, অন্য যে bool, ফাংশন ব্যবহার করে মূল্যায়ন করা হয় সত্য হয়ে যায় এবং ফিরে আসবে: 1
জয়রিজো

@ জয়রিজ্জো আমি এটি পেয়েছি এবং তারা উভয়ই বেশিরভাগ ক্ষেত্রে কার্যত একই রকম । তবে এর অর্থ আপনি সিঙ্গলটন তুলনা ব্যবহার করতে পারবেন না, অর্থাত্‍ 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লিনাক্স, Mac বা Windows।

দস্তাবেজ: http://click.pocoo.org/5/prompts/#confirmation-prompts


24

@ আলেকজান্ডার আর্টেমেনকো দ্বারা উল্লিখিত হিসাবে, এখানে স্ট্র্টোবুল ব্যবহার করে একটি সহজ সমাধান's

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 স্ট্যাকওভারফ্লো.comraw_inputinput
ব্রায়ান টিঙ্গল

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 সামঞ্জস্যপূর্ণ আরও পাইথনিক দ্বারা fmark এর উত্তর পরিবর্তন করেছি।

আপনি যদি আরও ত্রুটি পরিচালনার সাথে কোনও বিষয়ে আগ্রহী হন তবে আইপথনের ইউটিলিটি মডিউলটি দেখুন

# 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

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

না, এটি কাজ করে না। একাধিক উপায়ে আসলে। বর্তমানে এটি ঠিক করার চেষ্টা করছেন, তবে আমি মনে করি এটি সম্পন্ন হওয়ার পরে এটি অনেকটা গৃহীত উত্তরের মতো দেখাবে।
গর্মাডোর

আমি আপনাকে @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
যুক্তিটিকে "উত্তর" না দিয়ে "প্রশ্ন" বলা উচিত?
এএফপি_৫৫৫


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()
আমাদের সাইট ব্যবহার করে, আপনি স্বীকার করেছেন যে আপনি আমাদের কুকি নীতি এবং গোপনীয়তা নীতিটি পড়েছেন এবং বুঝতে পেরেছেন ।
Licensed under cc by-sa 3.0 with attribution required.