Python ArgumentParser method
What is Parser?
Parser is a component that reads structured data and converts it into a format that a program can understand. In python argument parser is used to parse command-line arguments passed to script.
What is argparse in python?
The argparse is built-in python module that makes it easy to handle command-line arguments. Instead of manually reading sys.argv, it provides structured way to accept and validate arguments.
Why use argparse?
To create user friendly command line interface by using argparse we can create better command line tools. we can create automatic help messages using --help method. It ensures correct argument types. we can set default argument values if an argument is missing.
How to use argparse in Python?
step1: To use argparse first we have to install package. we can use this command to install package command : pip install argparse.
step 2. import argpars
step 3: Create parser and define arguments
parser = argpars.ArgumentParser(description= " A script to parse number")
parser.add_argument("num1", type=int, help="first number")
parser.add_argument("num2", type=int, help="second number")
parser.add_argument("operation", choices=["add","sub"], default="add", help="Operation to perform add or sub operation")
args = parser.pars_args() # pars defined aruments
# use Parsed arguments
if args.operation == "add":
result = args.nim1 + args..num2
else:
result =aargs.num1 - args.num2
print(result)
How to call or use above arguments:
python script.py 10 5 --operation sub #we can run python script using this command.
python script.py --help # this is used to generate help messages automatically.
Key points: The. num1, num2 are the positional arguments . The --operation is the operational argument and. the int is the data type The default is assigns a value if no value is given. The --help shows the automatic generated documentation.
Difference between sys.argv and argparse
The argv is a list its supports by sys module and it support string format only.
Common Errors: index out of range, type errors
import systry:num1 = int(sys.argv[1])num2 = int(sys.argv[2])name = sys.argv[3]print("input values:", num1, num2, name)except ValueError as ex:print("Error:",ex)sys.exit(1)