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

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

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

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


当前回答

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

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

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

其他回答

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

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。

对于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]: ")
        try:
            return bool(strtobool(user_input))
        except ValueError:
            print("Please use y/n or yes/no.\n")

函数的作用是:将字符串转换为bool类型。如果字符串不能被解析,它将引发ValueError。

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

正如Geoff所说,strtoool实际上返回0或1,因此结果必须转换为bool类型。


这是strtobool的实现,如果你想让特殊的单词被识别为true,你可以复制代码并添加自己的case。

def strtobool (val):
    """Convert a string representation of truth to true (1) or false (0).
    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
    'val' is anything else.
    """
    val = val.lower()
    if val in ('y', 'yes', 't', 'true', 'on', '1'):
        return 1
    elif val in ('n', 'no', 'f', 'false', 'off', '0'):
        return 0
    else:
        raise ValueError("invalid truth value %r" % (val,))

我会这样做:

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

您可以使用单击的确认方法。

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

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

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