Tutorials Logic, IN info@tutorialslogic.com

Python Command Line Arguments with argparse

Command Arguments

Command line arguments let a script receive values when it starts.

Use argparse when a script needs named options, help text, defaults, or required values.

Arguments make automation scripts easier to reuse because users do not need to edit the source code for every run.

Argument Parser

argparse builds a small command-line interface and converts text arguments into named values.

  • Create one ArgumentParser.
  • Add each argument with a clear name.
  • Read parsed values from args.

Name Argument

Name Argument
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--name", required=True)
args = parser.parse_args()

print(f"Hello, {args.name}")

Run the file with --name Maya to pass a value from the terminal.

Defaults and Types

Arguments arrive as text, so use type= when the program needs an integer, float, or other conversion.

  • Use default for optional values.
  • Use type=int for numbers.
  • Use action="store_true" for simple on/off flags.

Limit Option

Limit Option
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--limit", type=int, default=10)
args = parser.parse_args()

print(f"Reading {args.limit} rows")

If --limit is missing, the script uses 10.

Before you move on

Can You Use Command Arguments?

5 checks
  • You can choose argparse instead of manual sys.argv parsing.
  • You can create required and optional arguments.
  • You can set defaults and convert number arguments.
  • You can add helpful names so --help is useful.
  • You can keep script configuration outside the source code.

Argument Parsing Traps

  • Reading sys.argv positions blindly

    Use argparse for named values and automatic help text.
  • Forgetting type conversion

    Add type=int or another converter when the value is not meant to stay as text.
  • Using unclear flag names

    Choose names that describe the value: --input, --output, --limit, or --dry-run.

Try this next

Parse a Command

0 of 3 completed

  1. Accept --name and --uppercase, then print the greeting in normal or uppercase form.
  2. Accept --input and check whether the path exists before reading.
  3. Add help= text to two arguments and run the script with --help.

Questions About Command Arguments

sys.argv is useful to understand, but argparse is better for real scripts because it gives names, validation, defaults, and help text.

It reads the file path as an argument. Your code still opens and validates the file.

A flag is usually an option such as --verbose or --dry-run that changes behavior without needing a separate value.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.