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

我的意思是,当包管理器提示一个yes/no问题,后面跟着[yes/no]时,脚本接受yes/ Y/yes/ Y或Enter(默认为yes,由大写字母提示)。

我在官方文档中唯一找到的是input和raw_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')

使用

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

其他回答

这是我对它的看法,我只是想中止如果用户没有确认的行动。

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

一个非常简单(但不是很复杂)的方法是:

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。

我知道这已经被回答了很多方法,这可能不能回答OP的具体问题(标准列表),但这是我为最常见的用例所做的,它比其他回答简单得多:

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

作为一个编程新手,我发现上面的一堆答案过于复杂,特别是如果目标是有一个简单的函数,你可以传递各种是/否问题,迫使用户选择是或否。在浏览了这篇文章和其他几篇文章,并借鉴了各种各样的好想法后,我得出了以下结论:

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

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

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