I am using aprgeparse in my program where to create an argument which allows the user to delete a file from a amazon s3 bucket. I create it in this way:
parser.add_argument("-r", "--remove",type = str, help= "Delete a file (enter full path to file)" , default = '' )
I then check if the file is available, if yes i delete it:
if args.remove:
b = Bucket(conn,default_bucket)
k = Key(b)
if b.get_key(args.remove):
b.delete_key(args.remove)
print ( ' {0} Has been removed'.format(args.remove.split("/")[-1]) )
else:
print ( " No files named '{0}' found ".format(args.remove.split("/")[-1] ) )
print ( ' Please check the bucket path or file name. Use -l command to list files')
I wanted to know if there is way I can prompt the user if he really intends the user to delete the file which is usually the case for deleting files (every program does it). Something like this
>python myprog.py -r foo.txt
>Are your sure [Y/N] : Y
>File deleted
I had the same issue (In a different CLI). I would suggest you to use the answer given here. Look at the answer given by James. Its fairly easy to understand. Use it like this:
if args.remove:
b = Bucket(conn,default_bucket)
k = Key(b)
if b.get_key(args.remove):
if yes_no('Are you sure: ')
b.delete_key(args.remove)
print ( ' {0} Has been removed'.format(args.remove.split("/")[-1]) )
else:
print ( " No files named '{0}' found ".format(args.remove.split("/")[-1] ) )
print ( ' Please check the bucket path or file name. Use -l command to list
From reading the docs I would use the ability to subclass argparse.Action to do your custom behavior when you see that argument. I will include a slightly modified version of the code in the docs for you to use.
class CheckDeleteAction(argparse.Action):
def __init__(self, option_strings, dest, nargs=None, **kwargs):
if nargs is not None:
raise ValueError("nargs not allowed")
super(CheckDeleteAction, self).__init__(option_strings, dest, **kwargs)
def __call__(self, parser, namespace, values, option_string):
# put your prompting and file deletion logic here
pass
Add this parser.add_argument("-r", "--remove", type=str, help="msg", default='', action=CheckDeleteAction) to make use of the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With