Introduction..
Python has a very powerful argparse module which provides functions for parsing command line arguments. If we want to get the user input from the OS command line without a lot of interaction or code a program that accepts parameters from the command line e.g. Provide a URL to parse or accepts the file to upload to a S3 bucket then argparse can be used with minimal effort.
Basic Usage
Define the arguments that your code is going to accept.
Call the argument parser to return the results object.
Use the arguments.
In short, the structure of argument parser looks some thing like below.
def main( parameters): << Logic here >> if __name__ == '__main__': << 1. Define argument parser >> << 2. Parse the arguements >> << 3. Validation >> << 4. call main (parameters) >>
The main function knows what the entry point of our code is. The __name__ == '__main__' section is executed only if the code is called directly.
Create a program which will accept only one argument - tennis players as string.
import argparse def get_args(): """ Function : get_args parameters used in .add_argument 1. metavar - Provide a hint to the user about the data type. - By default, all arguments are strings. 2. type - The actual Python data type - (note the lack of quotes around str) 3. help - A brief description of the parameter for the usage """ parser = argparse.ArgumentParser( description='Example for Two positional arguments', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Adding our first argument player name of type string parser.add_argument('player', metavar='player', type=str, help='Tennis Player') return parser.parse_args() # define main def main(player): print(f" *** The {player} had won 20 grandslam titles.") if __name__ == '__main__': args = get_args() main(args.player)
a) Now when you execute this program from the command line without passing any parameters i.e. If given nothing, it will print a brief usage statement about the proper way to invoke the program.
In [3]: run <>.ipynb usage: ipython [-h] player ipython: error: the following arguments are required: player An exception has occurred, use %tb to see the full traceback.
b) If we provide more than one argument, it complains again.The program complains about getting a second argument that has not been defined.
c) Only when we give the program exactly one argument will it run
2. Create a program which will accept only two arguments - tennis players as string and grand slamt titles won by the player as integer.
Example
import argparse def get_args(): """ Function : get_args parameters used in .add_argument 1. metavar - Provide a hint to the user about the data type. - By default, all arguments are strings. 2. type - The actual Python data type - (note the lack of quotes around str) 3. help - A brief description of the parameter for the usage """ parser = argparse.ArgumentParser( description='Example for Two positional arguments', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Adding our first argument player name of type string parser.add_argument('player', metavar='player', type=str, help='Tennis Player') # Adding our second argument player titles of type integer/number. parser.add_argument('titles', metavar='titles', type=int, help='Tennis Player Grandslam Titles') return parser.parse_args() # define main def main(player, titles): print(f" *** The {player} had won {titles} grandslam titles.") if __name__ == '__main__': args = get_args() main(args.player, args.titles)
Now open your terminal and execute the program. If the arguments are not passed, the script throw back error with clear message.
Output
<<< python test.py usage: test.py [-h] player titles test.py: error: the following arguments are required: player, titles <<< python test.py federer 20 *** The federer had won 20 grandslam titles.