Project Holy_Python_Grail_Quest - Argparse

In this post, I'll be sharing my notes on Argparse module on python. I've come across argparse module while working on my project. After googling, I've found this great tutorial at official python website: https://docs.python.org/2/howto/argparse.html. If you go through this, you'll get a very good idea about argparse and its usage.

I'm just posting this as a summarized version of what I've understood from the tutorial. Anyone can go through this for quick reference.


  1. Introducing Positional Arguments
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number",
                    type=int)
args = parser.parse_args()
print args.square**2
  • add_argument - To specify command line arguments the program is willing to accept
  • parse_args() - returns some data from the options specified
  • help - gives an idea about what the argument does
  • argparse - treats the option as strings unless mentioned otherwise. 
  • type - mentions to treat the input as an integer.
    2. Introducing Optional Arguments:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", help="increase output verbosity",
                    action="store_true")
args = parser.parse_args()
if args.verbose:
   print "verbosity turned on"
  • Optional argument - Shows no error when the program is run without specifying it.
  • action="store_true" - Makes it act as a flag. That is when the option is mentioned, it assumes the true value and prints "verbosity turned on". Not specifying it implies false.
   3. Short Options:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", help="increase output verbosity",
                    action="store_true")
args = parser.parse_args()
if args.verbose:
    print "verbosity turned on"
  • add_argument - add "-v" in first position or anything as per your wish to specify the short option.
    4. Combining Positional and Optional Arguments:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
    print "the square of {} equals {}".format(args.square, answer)
elif args.verbosity == 1:
    print "{}^2 == {}".format(args.square, answer)
else:
    print answer
  • choices - restricts the values --verbosity can take. Change is also reflected in the error message as well as help option.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", action="count", default=0,
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity >= 2:
    print "the square of {} equals {}".format(args.square, answer)
elif args.verbosity >= 1:
    print "{}^2 == {}".format(args.square, answer)
else:
    print answer
  • default - By setting it to 0, we make sure that an int value is assigned to it and make it comparable in conditional statements. So, that when no optional argument is assigned, no error is thrown.
  • action="count" - counts the number of times '-v' appears in the command and based on that prints message
   5. Advanced functions:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
parser.add_argument("-v", "--verbosity", action="count", default=0)
args = parser.parse_args()
answer = args.x**args.y
if args.verbosity >= 2:
    print "Running '{}'".format(__file__)
if args.verbosity >= 1:
    print "{}^{} ==".format(args.x, args.y),
print answer

Output:


$ python prog.py 4 2
16
$ python prog.py 4 2 -v
4^2 == 16
$ python prog.py 4 2 -vv
Running 'prog.py'
4^2 == 16

The above example shows more advance functionality of the sample program. Here, the file name is displayed when '-v' count is more than 2 and overall, two arguments are taken as base and exponent to find different set of powers.

 6. Conflicting Options:


import argparse

parser = argparse.ArgumentParser(description="calculate X to the power of Y")
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
args = parser.parse_args()
answer = args.x**args.y

if args.quiet:
    print answer
elif args.verbose:
    print "{} to the power {} equals {}".format(args.x, args.y, answer)
else:
    print "{}^{} == {}".format(args.x, args.y, answer)
  • description - Gives an idea to user about the functionality of the program
  • add_mutually_exclusive_group () - To specify options that conflict with each other. These options can't be used together. 
Hope this summarized notes will be helpful for someone (most likely me) in quickly getting an idea about argparse module. For more detailed tutorial, please refer the link I mentioned above.

PS: This is my 48th post. Its quite a feat considering a year back I've completely lost interest in programming.

Ciao.
MG.

Comments

Popular posts from this blog

Project Wild Penguin 12.4.2017: Installing Broadcom Wireless Drivers to connect to JBL Bluetooth Speaker on Xubuntu 16.10

Project Wild Penguin 22.4.2017: To delete directories inside current directory whose contents are less than a given size

ANPR Project Day 1: Standard Format of Indian Number Plate