Table of Contents

    argparse

    PYTHON & CLI

    Python argparse — The Complete Guide

    Master argparse to build professional command-line interfaces with arguments, options, flags, help text, and automatic validation.

    Introduction

    argparse is Python's built-in module for parsing command-line arguments. It lets your script accept inputs from the terminal — positional arguments, optional flags, and typed values — while automatically generating help messages, validating input, and producing clean error messages. Instead of manually reading sys.argv and writing fragile parsing logic, argparse gives you a robust, self-documenting CLI with just a few lines of code.

    In one line: argparse turns terminal input into validated Python variables — with free help text and error handling.

    Real-World Analogy

    The Order Form at a Counter

    Instead of shouting a jumble of requests, you fill out a structured order form with labelled fields — required items, optional extras, quantities. The clerk validates it and rejects anything invalid. argparse is that order form for your program: it defines exactly what inputs are accepted and checks them before your code runs.

    Prerequisites

    Before You Start

    • Python 3.x installed
    • Understanding of functions and running scripts from the terminal
    • The module is built in — just import argparse
    • Basic familiarity with the command line (running python script.py)
    • Awareness of sys.argv (helpful for comparison)

    The Problem It Solves

    Reading sys.argv manually is error-prone and lacks validation or help text.

    import sys
    
    # Manual parsing — fragile and unfriendly
    name = sys.argv[1]          # crashes if missing
    age = int(sys.argv[2])      # no validation, cryptic errors
    print(name, age)
    With argparse You get typed arguments, validation, help text, and clear error messages automatically.

    Your First Parser

    The three core steps: create a parser, add arguments, then parse them.

    import argparse
    
    # 1. Create the parser
    parser = argparse.ArgumentParser(description="Greet a user")
    
    # 2. Add arguments
    parser.add_argument("name", help="the user's name")
    parser.add_argument("--age", type=int, help="the user's age")
    
    # 3. Parse the command line
    args = parser.parse_args()
    
    print(f"Hello {args.name}!")
    if args.age:
        print(f"You are {args.age} years old.")
    $ python greet.py Rumman --age 30
    Hello Rumman!
    You are 30 years old.
    
    $ python greet.py --help
    usage: greet.py [-h] [--age AGE] name
    ...

    Positional vs Optional Arguments

    1

    Positional Arguments

    Required, identified by position.

    parser.add_argument("filename") — the user must supply it, and its order matters.

    2

    Optional Arguments

    Prefixed with - or --.

    parser.add_argument("--verbose") — optional and identified by name, not position.

    Key add_argument Parameters

    Parameter Purpose
    type Convert the input (e.g. int, float)
    default Value used if the argument is omitted
    help Description shown in --help
    required Make an optional argument mandatory
    choices Restrict input to a fixed set of values
    action Special behaviour (e.g. store_true for flags)
    nargs Number of values the argument consumes
    metavar Display name for the value in help

    Boolean Flags with store_true

    Use action="store_true" for on/off switches that need no value.

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument("--verbose", action="store_true", help="enable verbose output")
    args = parser.parse_args()
    
    if args.verbose:
        print("Verbose mode ON")
    $ python app.py --verbose
    Verbose mode ON
    
    $ python app.py
    # (nothing — verbose defaults to False)

    Types, Defaults, and Choices

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument("--count", type=int, default=1, help="number of times")
    parser.add_argument(
        "--mode",
        choices=["fast", "slow", "auto"],   # only these are allowed
        default="auto",
    )
    args = parser.parse_args()
    
    print(args.count, args.mode)
    Auto-validation Passing --mode turbo triggers an automatic error: invalid choice: 'turbo'.

    Multiple Values with nargs

    nargs controls how many values an argument accepts.

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument("numbers", type=int, nargs="+", help="one or more numbers")
    args = parser.parse_args()
    
    print(sum(args.numbers))
    $ python sum.py 3 5 7
    15
    nargs Value Meaning
    N (an int) Exactly N values (as a list)
    "?" Zero or one value
    "*" Zero or more values
    "+" One or more values (at least one required)

    Short and Long Option Names

    Give an argument both a short (-v) and long (--verbose) form.

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument("-o", "--output", help="output file path")
    args = parser.parse_args()
    
    print(args.output)   # accessed by the long name

    Subcommands with add_subparsers

    Build git-style CLIs (tool add, tool remove) using subparsers.

    import argparse
    
    parser = argparse.ArgumentParser(prog="tool")
    subparsers = parser.add_subparsers(dest="command")
    
    # "add" subcommand
    add = subparsers.add_parser("add", help="add an item")
    add.add_argument("item")
    
    # "remove" subcommand
    remove = subparsers.add_parser("remove", help="remove an item")
    remove.add_argument("item")
    
    args = parser.parse_args()
    
    if args.command == "add":
        print(f"Adding {args.item}")
    elif args.command == "remove":
        print(f"Removing {args.item}")
    $ python tool.py add book
    Adding book

    Argument Combinations

    Each boolean flag doubles the number of possible invocations. With \(f\) independent on/off flags, the number of distinct flag combinations is:

    \[ N_{\text{combinations}} = 2^{f} \]

    This is why clear --help text and sensible defaults matter — a handful of flags creates many possible states to reason about.

    Best Practices

    Do This

    • Always add a helpful description and per-argument help text
    • Use type to convert and validate inputs automatically
    • Use choices to restrict inputs to valid options
    • Provide sensible default values for optional arguments
    • Use action="store_true" for boolean flags
    • Wrap logic in a main() and call parse_args() under if __name__ == "__main__"

    Common Mistakes

    Bad Forgetting type=int — all arguments come in as strings, so args.count + 1 fails or concatenates.
    Good Specify type=int (or float) so the value is converted before your code uses it.
    Bad Using a hyphen in the dest name expecting args.my-flag — Python converts --my-flag to args.my_flag.
    Good Access it as args.my_flag (hyphens become underscores automatically).

    Interview Questions

    Question Short Answer
    What is argparse? Python's built-in module for parsing command-line arguments with validation and help.
    Positional vs optional argument? Positional is required by order; optional uses -/-- and is name-based.
    How do you make a boolean flag? Use action="store_true".
    What does nargs do? Controls how many values an argument consumes (+, *, ?, N).
    How do you build subcommands? Use add_subparsers() to create git-style commands.

    Quick Revision

    Goal Code
    Create parser argparse.ArgumentParser()
    Positional arg add_argument("name")
    Optional arg add_argument("--age", type=int)
    Boolean flag add_argument("--v", action="store_true")
    Parse args = parser.parse_args()

    Key Takeaways

    argparse builds professional CLIs in three steps: create a parser, add arguments, and parse. You get free help text, type validation, choices, flags, and subcommands — replacing fragile sys.argv parsing.