Python ‘argparser’ Library.


Python ‘argparse’ Library

Table Of Contents:

  1. What Is An ‘argparse’ Library?
  2. Why Do We Use ‘argparse’ Library?
  3. Syntax Used In ‘argparse’ Library?
  4. Parameters Passed To add_argument() Method.
  5. Example Of ‘argparse’ Library?

(1) What Is An ‘argparse’ Library?

  • ‘argparse’ library is a command line parsing module used while creating a user-friendly command line interface programming.
  • When you want your program to accept command line arguments from the command prompt, that time you will use ‘argparsr’ library.

(2) Why Do We Use ‘argparse’ Library ?

  • To accept command line input as an argument we can use the ‘argparse’ library.
  • By using the ‘argparse’ library we can program to accept the command line argument as an input parameter.

(3) Syntax Used In ‘argparse’ Library ?

  • Follow the below commands to use ‘argparse’ library.

Import Library:

import argparse

Create An Object Of Argument Parser:

parser = argparse.ArgumentParser()

Define The Variables To Store Input Arguments:

parser.add_argument("num1", help = "first number")
parser.add_argument("num2", help = "second number")  
parser.add_argument("operation", help = "operation")  

Runs The Parser:

args = parser.parse_args()  

Print The Input Values:

print(args.num1)  
print(args.num2)  
print(args.operation)  

Stores The Input Values:

n1 = int(args.num1)  
n2 = int(args.num2)  

Perform The Operations On Input Data:

if args.operation == "add":  
    result = n1 + n2  
    print("The Result is : ",result)  
  
elif args.operation == "sub":  
    result = n1 - n2  
  
elif args.operation == "mul":  
    result = n1 * n2  
elif args.operation == "div":  
    result = n1 / n2  
else:  
    print("Unmatched Argument")  
  
print("result is : ",result)  

Call The Python File Name With Input Arguments.

Analysis:

  • First, To the code.py file we have passed three arguments, 100, 50 and sub.
  • Second we are displaying the input values in the command line screen.
  • Third we are doing the operation.

(4) Parameters Passed To ‘add_argument’ method.

  • Follow the below commands to use ‘argparse’ library.

Leave a Reply

Your email address will not be published. Required fields are marked *