Search

25 May, 2018

How to use argparse module to create command line tools with Python?



Its been decades I have been using sys.argv for simple tasks related to argument parsing. But the thing is, sometimes we don't realize how good something is unless we use it . Like the argparse module.

The official document got me totally confused. So I wrote my own tutorial. Let's get started.


So the module to be imported is 'argparse'. First thing to do is , create a parser object.


parser = argparse.ArgumentParser()

Then we can add what arguments we want . These are the requirements.
  • I want a username. 
  • I also want to set a default.  If nothing is provided, then the default user will be used. 
  • If User name is provided , then that should be used. 
  • We should tell the user about this requirement through some kind of help instruction.

parser.add_argument("-user", default='Admin')

So to pass a username, one needs to use the '-user' option.

args = parser.parse_args()

Then we need to call the above. This will create a namespace.


>>> args
Namespace(user='Admin')


Note: The name space has the attribute 'user', not -user. This is done automatically. Similarly, - will be converted to underscore.

if args.user == 'Admin':
    print 'You nailed it!'
else:
    print 'This is a different user: ', args.user

Now we can use this to create some logic. That's it. So the whole program looks like this:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-user", default='Admin')

args = parser.parse_args()

if args.user == 'Admin':
    print 'You nailed it!'
else:
    print 'This is a different user: ', args.user


Arindam@TheArcs MINGW64 ~/Desktop/PyTrash
$ python argeparse_example.py
You nailed it!

This is how we use it. We call the program directly on the command line. We might provide some arguments or not. In above example, we didn't.


$ python argeparse_example.py -user User123
This is a different user:  User123


$ python argeparse_example.py --help
usage: argeparse_example.py [-h] [-user USER]

optional arguments:
  -h, --help  show this help message and exit
  -user USER

If no help description is provided, we can still use the -h or --help argument to invoke default created help. If we want to add some help instructions, we can use the description argument.


parser = argparse.ArgumentParser(description='Please enter a user name')


$ python argeparse_example.py --help
usage: argeparse_example.py [-h] [-user USER]

Please enter a user name

optional arguments:
  -h, --help  show this help message and exit
  -user USER


No comments:

Post a Comment