APTコマンドラインインターフェイスのようなyes / no入力?


169

PythonでAPT(Advanced Package Tool)コマンドラインインターフェースが実行する簡単な方法はありますか?

つまり、パッケージマネージャーがはい/いいえの質問に続いてを要求する[Yes/no]と、スクリプトはYES/Y/yes/yまたはを受け入れますEnter(デフォルトでYesは大文字で示されます)。

私が公式ドキュメントで見つける唯一のものはinput、そしてraw_input...

エミュレートするのはそれほど難しいことではありませんが、書き換えるのは面倒です:|


15
Python 3ではraw_input()と呼ばれinput()ます。
東武

回答:


222

あなたが述べたように、最も簡単な方法は、使用することですraw_input()(または単にinput()のためにPythonの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、

良い選択イグナシオ、修正
fmark 2010年

24
実際、スタンダールライブラリ内の関数strtoboolがあります:docs.python.org/2/distutils/...
アレクサンダーArtemenko

14
ただ覚えておいてください: Python3 raw_input()で呼び出さinput()れます
nachouve

確かに超役立つ!ただ、交換する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()Python3 で呼び出されます
gizzmole

49

strtoboolPythonの標準ライブラリに関数があります:http : //docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool

これを使用して、ユーザーの入力を確認しTrueFalse値または値に変換できます。


fおそらくFalseを表していFalse == 0ます。なぜ関数がのint代わりにを返すのかboolは、私には謎です。
フランソワルブラン2018年

@FrançoisLeblancがデータベースで最も一般的である理由について。明示的Falseまたは0(ゼロ)でない場合。それ以外の場合、bool関数を使用して評価されるものはすべてtrueになり、を返します1
JayRizzo 2018年

@JayRizzo私はそれを理解しています、そしてそれらはほとんどの点で機能的に似ています。ただし、シングルトン比較を使用できないことを意味しますif strtobool(string) is False: do_stuff()
フランソワルブラン2018年

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
エントロピー2015

2
strtobool()(私のテストから)は必要ないことに注意してくださいlower()。ただし、これはドキュメントでは明示されていません。
マイケル-クレイシャーキーはどこですか

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)

これは、Python 2との仕事はしない- raw_inputと改名されたinput3 pythonでstackoverflow.com/questions/21122540/...
ブライアンチンクル

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
"default = 'no'"でプロンプターを使用する場合、プロンプターの動作はかなり逆になることに注意してください。「いいえ」を選択するとTrueが返され、「はい」を選択するとFalseが返されます。
rem

7

私はfmarkの答えをpython 2/3互換のもっとpythonicに変更しました。

エラー処理の詳細に興味がある場合は、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の両方と互換性があり、非常に読みやすいです。私はこの答えを使用してしまいました。
フランソワルブラン2018年

4

2.7では、これはPythonicではありませんか?

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

anwser @pjmを編集しました。それを検討することを検討してください:-)
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が発生します。

Python 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

プログラミングの初心者として、私は上記の答えの束が過度に複雑であることを発見しました。特に、目標がさまざまなはい/いいえの質問を渡して、ユーザーにはいまたはいいえを選択させる単純な関数を持つことである場合は特にそうです。このページと他のいくつかのページを精査し、さまざまな良いアイデアをすべて借りた後、私は次のようになりました:

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 2018年

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.