我正在用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
,并直接删除文件。我不知道该怎么做。任何帮助都将不胜感激
在argparser中需要一个解析操作
store_true
。你知道吗现在您可以检查
y
的值并决定是否需要向用户请求提示。我认为,您可能应该使用比y
更具描述性的选项。例如noprompt
。你知道吗相关问题 更多 >
编程相关推荐