Command line utility

#there are two types of command line arguments are there
#1. positional arguments
#- we can give value arguments directly in WPS (windows powershell)
#- cant skip any value argument
#- expected command in WPS for command line argument program execution ( 4 6 add [note:cant change position])

#2. optional arguments
#- we have to give value arguments in WPS with (--argument_name argument_value)
#- we can skip any value argument
#- expected command in WPS for program execution (--number1 4 --number2 6 --operation add [note:can change position])

import argparse #python built in library
import sys
if __name__=='__main__':
parser=argparse.ArgumentParser() #parser object
# 1. positional arguments
# using add_argument function or attribute adding arguments
'''parser.add_argument("num1", help="first number")
parser.add_argument("num2", help="second number")
parser.add_argument("operation", help="operation")'''

#'''
#2. optional arguments
# using add_argument function or attribute of parser object adding arguments
#parameters of add_argument function (argument_name, type, default, help)
parser.add_argument("--num1", type= int, default= 10, help="first number or contact harish")
parser.add_argument("--num2",type= int,default=5, help="second number or contact harish")
parser.add_argument("--operation", type=str,default= "add", help="operation or contact harish")
#'''
#using parse_args function or attribute of parser object parsing arguments
args=parser.parse_args()
#printing output argument values
print(args.num1)
print(args.num2)
print(args.operation)

#converting arguments value to int because they are by default strings
n1=int(args.num1)
n2=int(args.num2)
result=None
if (args.operation) == "add":
result= n1+n2
elif (args.operation)== "sub":
result= n1-n2
elif (args.operation)== "mul":
result= n1*n2
elif (args.operation)== "div":
result= n1/n2
else:
print("unsupported operation")

print("result:", result)
sys.stdout.write(str(result)) #code to throw the output by sys module



Comments

Popular posts from this blog

Steps taken by a compiler to execute a C program

Tokens in C

Variables and Data Types in C