📋 Argparse Module

Last Updated: 21th August 2025


The argparse module is used for command-line arguments. Instead of taking input with input(), you can run your Python script with arguments like this:

python my_script.py --arg1 value1 --arg2 value2

List of Functions:

  • ArgumentParser(): Creates an ArgumentParser object.
import argparse
parser = argparse.ArgumentParser(description="My First CLI Program")
print(parser)
  • parser.add_argument(): Add arguments that script will accept.Positional arguments are arguments that are required to run the script,Syntax.
import argparse
parser.add_argument("filename", help="Name of the file to process")

#In command line
#python script.py data.csv
  • parser.add_argument(): Optional Argument (with flag), Syntax:
import argparse
parser.add_argument("--verbose", action="store_true",type=datatype, required=bool,default=defaultValue, help="Enable verbose output")
print(parser)
# In command line
#python script.py --verbose
  • parser.parse_args():Collects all arguments when script is run.
args = parser.parse_args()
print(args.filename)
print(args.verbose)

Example 1:

# calc.py
import argparse

# 1. Create parser
parser = argparse.ArgumentParser(description="Simple Calculator CLI")

# 2. Add positional arguments
parser.add_argument("num1", type=int, help="First number")
parser.add_argument("num2", type=int, help="Second number")

# 3. Add optional argument
parser.add_argument("--operation", choices=["add", "sub", "mul", "div"],
                    default="add", help="Operation to perform")

# 4. Parse the arguments
args = parser.parse_args()

# 5. Perform operation
if args.operation == "add":
    result = args.num1 + args.num2
elif args.operation == "sub":
    result = args.num1 - args.num2
elif args.operation == "mul":
    result = args.num1 * args.num2
elif args.operation == "div":
    result = args.num1 / args.num2

print(f"Result: {result}")

in command line

# default operation is add
python calc.py 10 5
Result: 15

# specify operation
python calc.py 10 5 --operation sub
Result: 5

# help menu(auto generated)
python calc.py -h

Example 2:

#csv_analyzer.py
import argparse

parser = argparse.ArgumentParser(description="CSV Analyzer")
parser.add_argument("filename", help="CSV file name")
parser.add_argument("--delimiter", default=",", help="CSV delimiter")
parser.add_argument("--header", type=int, default=0, help="Row number of header")

args = parser.parse_args()
print(f"Processing {args.filename} with delimiter {args.delimiter}")

in command line

python csv_analyzer.py data.csv --delimiter ";" --header 1

📝 Quick Practice

  • Create a script that takes two numbers and prints their sum.
  • Add an optional argument --square which, if provided, prints the square of the sum.
  • Add a required argument --username.