Exception
Exception

Reputation: 25

How do I easily store a file and folder location with argparse and then use those values

I have Python module/script (depends what you read) I want to open a file and extract the contents to a directory, it works fine by using file=sys.argv[1] and folder=sys.argv[2] for example but I'd like to use argparse for ease of use for end users.

if len(sys.argv) < 2:
    print "Usage: '%s -h'" % sys.argv[0]
    sys.exit(0)

def untar():
    #Both these values to come from argparse
    tarloc = tfile
    dest = folder

    #tarloc = sys.argv[1]
    #dest = sys.argv[2]
    filecount = 0
    tar = tarfile.open(tarloc)
    ....etc

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Module to untar TAR files')
    parser.add_argument('-f', "--file", help='File to open', action="store_true", dest="tfile")
    parser.add_argument('-d', "--dest", help='Destination to extract to', action="store_true", dest="folder")
    args = parser.parse_args()
    print args

Could someone please assist me with showing how you get argparse to store args and then how you use them.

Also should argparse be above or below the if __name__ == section?

Upvotes: 0

Views: 308

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121524

Both your file and destination arguments are mandatory; if the user did not specify them your script would have nothing to do.

So don't use - or -- options here, you want positional arguments:

parser = argparse.ArgumentParser(description='Module to untar TAR files')
parser.add_argument('file', help='File to open')
parser.add_argument('folder', help='Destination to extract to')
args = parser.parse_args()

Note that I removed the action arguments; store_true is for boolean flag options; e.g. if the user specifies the flag on the command line, something is switched on, no arguments are taken.

Next, pass those file and folder values to your function:

def untar(tarloc, folder):
    filecount = 0
    tar = tarfile.open(tarloc)
    # ....etc

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Module to untar TAR files')
    parser.add_argument('file', help='File to open')
    parser.add_argument('folder', help='Destination to extract to')
    args = parser.parse_args()
    untar(args.file, args.folder)

You may want to follow the argparse tutorial included in the Python documentation for more details.

Upvotes: 3

Related Questions