Python CLI - 对所有用户问题回答是

Python CLI - Answer yes to all user questions

我正在python中写一个CLI。在很多情况下,我都会要求用户进行确认。例如 - 如果调用了 delete 参数,我会在删除文件之前要求用户进行确认。但是,我想添加另一个参数,如 -y (yes),这样如果使用 -y,我不希望提示用户并继续删除他指定的文件。 我在这里发布相关代码:

def yes_no(userconfirmation):

    """     
    Converts string input and returns a boolean value.
    """

    stdout.write('%s [y/n] : ' % userconfirmation)
    while True:
        try:
            return strtobool( raw_input().lower() )
        except ValueError:
            stdout.write( 'Please respond with \'y\' or \'n\'.\n' )

#In the delete function:

if yes_no( 'Are you sure you want to delete {0}'.format( file_to_remove.split("/")[-1] ) ):
                        b.delete_key(file_to_remove)

当我调用python myprog.py -r file_to_remove.txt时如果提示Are you sure you want to delete file_to_delete.py [y/n]。如果我按下 y 文件被删除,如果按下 n 文件删除被中止。我希望能够使用不提示用户输入 y/npython myprog.py -r file_to_remove.txt -y 并直接删除文件。我不确定如何执行此操作。任何帮助将不胜感激

您的 argparser 中需要一个解析操作 store_true

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-y', action='store_true')
>>> parser.parse_args('-y'.split())
Namespace(y=True)
>>> parser.parse_args(''.split())
Namespace(y=False)
>>> 

现在您可以检查 y 的值并决定是否需要向用户询问提示。我认为您可能应该使用比 y 更具描述性的选项作为选项。例如 --noprompt.

>>> parser.add_argument('-n', '--noprompt', action='store_true')
>>> parser.parse_args(''.split())
Namespace(noprompt=False)
>>> parser.parse_args('--noprompt'.split())
Namespace(noprompt=True)
>>> parser.parse_args('-n'.split())
Namespace(noprompt=True)