Python CLI对所有用户问题回答yes

2024-09-27 00:17:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用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,则中止删除文件。我希望能够使用python myprog.py -r file_to_remove.txt -y,它不会提示用户输入y/n,并直接删除文件。我不知道该怎么做。任何帮助都将不胜感激


Tags: 文件tono用户pyyouinput参数
1条回答
网友
1楼 · 发布于 2024-09-27 00:17:46

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

相关问题 更多 >

    热门问题