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

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

我在官方文档中唯一找到的是input和raw_input…

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


当前回答

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

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

其他回答

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

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。

我会这样做:

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

我知道这已经被回答了很多方法,这可能不能回答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(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

在2.7中,这是不是太非python化了?

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

它至少能捕捉到“是”的任何变化。