APT命令行界面 - 是/否输入?

时间:2010-06-15 01:13:54

标签: python

有没有简短的方法来实现APT(高级软件包工具)命令行界面在Python中的作用?

我的意思是,当包管理器提示是{/ 1}}之后的是/否问题时,脚本接受[Yes/no]输入(默认为YES/Y/yes/y为大写字母暗示。)

我在官方文档中找到的唯一内容是Yesinput ......

我知道这并不难以模仿,但重写很烦人:|

22 个答案:

答案 0 :(得分:193)

正如您所提到的,最简单的方法是使用raw_input()(或input()只使用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") )。没有内置的方法来做到这一点。来自Python 3

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

用法示例:

{{1}}

答案 1 :(得分:86)

我这样做:

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

答案 2 :(得分:45)

Python的标准库中有一个函数strtoboolhttp://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool

您可以使用它来检查用户的输入并将其转换为TrueFalse值。

答案 3 :(得分:41)

答案 4 :(得分:30)

您可以使用clickconfirm方法。

import click

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

这将打印:

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

适用于Linux,Mac或Windows上的Python 2/3

文档:http://click.pocoo.org/5/prompts/#confirmation-prompts

答案 5 :(得分:21)

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

答案 6 :(得分:15)

我知道这已经回答了很多方法,这可能无法解决OP的具体问题(使用标准列表)但这是我为最常见的用例所做的事情,它比其他答案简单得多:< / p>

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

答案 7 :(得分:7)

您也可以使用prompter

无耻地从自述文件中获取:

#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

答案 8 :(得分:6)

我修改了fmark的答案,通过python 2/3兼容更多pythonic。

如果您对错误处理更多的内容感兴趣,请参阅ipython's utility module

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

答案 9 :(得分:4)

在2.7上,这是不是非pythonic?

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

它至少捕获了Yes的任何变体。

答案 10 :(得分:4)

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

答案 11 :(得分: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

答案 12 :(得分:2)

对于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函数将字符串转换为bool。如果字符串无法解析,则会引发ValueError。

在Python 3中,raw_input已重命名为input

答案 13 :(得分: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')

答案 14 :(得分: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

答案 15 :(得分: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'

答案 16 :(得分: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()

答案 17 :(得分: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

答案 18 :(得分:0)

一个清理过的Python 3示例:

//@version=4
study("Time begin", "", true)

// #1
timeOpen1 = hour == 9
timeOpenOk1 = not timeOpen1[1] and timeOpen1
plotchar(timeOpenOk1, "timeOpenOk1", "", location.abovebar, text = "▲")
plotchar(timeOpen1, "timeOpen1", "", location.belowbar, text = "•")

// #2
sessSpec2 = input("0900-0959", type=input.session) + ":1234567"
is_newbar(res, sess) =>
    t = time(res, sess)
    na(t[1]) and not na(t) or t[1] < t
timeOpenOk2 = timeframe.isintraday and is_newbar("1440", sessSpec2)
plotchar(timeOpenOk2, "timeOpenOk2", "", location.abovebar, color.orange, text = "▲\n‎")

答案 19 :(得分:0)

Python 3.8及更高版本的单行代码:

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

答案 20 :(得分:0)

Python x.x

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

答案 21 :(得分:0)

由于预期答案是yes或no,在下面的例子中,第一个解决方案是使用函数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()