Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argeparse confirmation

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
like image 467
letsc Avatar asked Jun 11 '26 08:06

letsc


2 Answers

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
like image 163
Beginner Avatar answered Jun 13 '26 22:06

Beginner


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.

like image 30
Muttonchop Avatar answered Jun 13 '26 22:06

Muttonchop