When you work on file which deals with many arguments, it is time consuming and not user friendly to always change those arguments inside the python file. Some libraries have been implemented to solve this problem, known as command line parsing library. In python, they are three different solutions: DocoptArgparse and Click.

In this article I will go in depth in the use of Docopt and not Argparse or Click. I made this choice because after having used all those three methods, I realized that Docopt is by far the most user-friendly way to parse arguments into a file.

The way I will present the Docopt library is by showing you an example of a docopt.py file with the setup.py and requirements.txt file that go with it.

#### docopt.py file 

'''
Usage:
docopt.py square [options] [operation] [square-option]
docopt.py rectangle [options] [operation] [triangle-option]
operation:
   --area=<bool>       Calculate the area if the argument==True
   --perimeter=<bool>  Calculate the perimeter if the argument==True
square-option:
   --edge=<float>      Edge of the square. [default: 2]
rectangle-option:
   --height=<float>    Height of the rectangle 
   --width=<float>     Width of the rectangle 
'''
from docopt import docopt
def area(args):
   """
   This method computes the area of a square or a rectangle 
   """   
   if bool(args['square']):
      if args['--edge']:
         area = float(args['edge']) ** 2
      else:
         print("You must specify the edge")
   elif bool(args['rectangle']):
      if args['--height'] and args['--width']:
         area = float(args['--height']) * float(args['--width'])
      else:
         print("You have forgotten to specify either the height or       the width or both")
   return area
def perimeter(args):
   """
   This method computes the perimeter of a square or a rectangle 
   """
   if bool(args['square']):
      if args['--edge']:
         perimeter = float(args['edge']) * 2
      else:
         print("You must specify the edge")
   elif bool(args['rectangle']):
      if args['--height'] and args['--width']:
         perimeter = float(args['--height']) + float(args['--width'])
      else:
         print("You have forgotten to specify either the height or       the width or both")
   return perimeter
def main():
   args = docopt(__doc__)
   if args['--area']:
      area(args)
   elif args['--perimeter']:
      perimeter(args)
   else:
      print("command not found")
if __name__=='__main__':
   main()

#python #python-programming #software-engineering #data-science

Using Docopt in python, the most user-friendly command-line parsing library
1.40 GEEK