Course topics

By WebNest Studio Engineering Team

Python Tutorial

Command-Line Arguments in Python

Command-line tools take their input as arguments: python resize.py photo.jpg --width 800 --quality 90. Python exposes raw arguments through sys.argv, and the standard argparse module turns them into a professional interface with types, defaults, validation, help text and sub-commands — no extra libraries needed.

This lesson covers sys.argv, argparse positional and optional arguments, flags, choices, multiple values and sub-commands, and mentions popular third-party alternatives.

Why it matters

Scripts become useful tools when they accept options: which file to process, how many times to retry, whether to print extra detail. argparse converts and checks the arguments, reports mistakes clearly and writes the --help text for you. Scheduled jobs and deployment scripts are run this way.

sys.argv

sys.argv is a list of strings: argv[0] is the script name and the rest are the arguments as typed. It is fine for tiny scripts, but you must convert types, check counts and write help messages yourself.

argparse Basics

Create an ArgumentParser, declare arguments with add_argument, and call parse_args(). Positional arguments are required and ordered; optional ones start with -- (and can have short forms like -w). Options include type=int, default, required=True, choices=[...], nargs="+" for several values, and action="store_true" for flags. --help is generated automatically, and invalid input produces a clear error with exit code 2.

Sub-commands and Alternatives

add_subparsers() creates git-style commands (tool add, tool list). For larger CLIs, third-party libraries such as Typer (built on type hints, by the creator of FastAPI) and Click offer decorators and richer features.

Examples

Reading raw arguments with sys.argv

Python
# greet.py
import sys

if len(sys.argv) < 2:
    print("usage: python greet.py NAME [TIMES]")
    sys.exit(1)

name = sys.argv[1]
times = int(sys.argv[2]) if len(sys.argv) > 2 else 1
for _ in range(times):
    print(f"Hello, {name}!")

# $ python greet.py Asha 2
Output
Hello, Asha!
Hello, Asha!

A complete argparse interface (parsing a sample argument list)

Python
import argparse

parser = argparse.ArgumentParser(description="Resize images for the website.")
parser.add_argument("files", nargs="+", help="image files to resize")
parser.add_argument("-w", "--width", type=int, default=800, help="target width in pixels")
parser.add_argument("--format", choices=["jpg", "png", "webp"], default="webp")
parser.add_argument("-v", "--verbose", action="store_true", help="print details")

# In a real script: args = parser.parse_args()  (reads sys.argv)
args = parser.parse_args(["a.jpg", "b.png", "--width", "1200", "-v"])
print(args)
print(args.files, args.width + 100, args.format, args.verbose)

try:
    parser.parse_args(["a.jpg", "--format", "gif"])
except SystemExit as e:
    print("exit code:", e.code)
Output
Namespace(files=['a.jpg', 'b.png'], width=1200, format='webp', verbose=True)
['a.jpg', 'b.png'] 1300 webp True
usage: main.py [-h] [-w WIDTH] [--format {jpg,png,webp}] [-v] files [files ...]
main.py: error: argument --format: invalid choice: 'gif' (choose from jpg, png, webp)
exit code: 2

Sub-commands like git

Python
import argparse

parser = argparse.ArgumentParser(prog="todo")
sub = parser.add_subparsers(dest="command", required=True)

add = sub.add_parser("add", help="add a task")
add.add_argument("title")
add.add_argument("--priority", type=int, default=2)

sub.add_parser("list", help="list tasks")

for argv in (["add", "Learn argparse", "--priority", "1"], ["list"]):
    args = parser.parse_args(argv)
    if args.command == "add":
        print(f"added {args.title!r} with priority {args.priority}")
    elif args.command == "list":
        print("listing tasks...")
Output
added 'Learn argparse' with priority 1
listing tasks...

Common Mistakes

  • Indexing sys.argv without checking its length (IndexError).
  • Forgetting that every sys.argv value is a string.
  • Writing custom help and validation that argparse provides for free.
  • Using positional arguments for optional settings instead of --options.

Exercise

Build an argument parser with a --name option and a --times option that is an integer with a default of 1. Parse the sample argument list given in the code, then print the greeting that many times.

Expected output: Hello, Asha! then Hello, Asha!

Python · starter code
import argparse

parser = argparse.ArgumentParser()
# TODO: add the --name option
# TODO: add the --times option (an int, default 1)

# A list is passed here so the result does not depend on how the script is started.
args = parser.parse_args(["--name", "Asha", "--times", "2"])

# TODO: print "Hello, <name>!" args.times times
Show hints
  • parser.add_argument("--times", type=int, default=1) converts the text to an integer.
  • The parsed values are attributes of the result: args.name and args.times.
Show solution
Python · solution
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--name")
parser.add_argument("--times", type=int, default=1)

# A list is passed here so the result does not depend on how the script is started.
args = parser.parse_args(["--name", "Asha", "--times", "2"])

for _ in range(args.times):
    print(f"Hello, {args.name}!")

Quick quiz

1. What type are the items of sys.argv?

  • A. str
  • B. int
  • C. They depend on what was typed
  • D. bytes
Show answer

A. Every argument arrives as text and must be converted if a number is needed.

2. What does argparse provide without any extra code?

  • A. A graphical window
  • B. A --help option listing the arguments
  • C. Automatic logging
  • D. A configuration file
Show answer

B. The help text is built from the arguments you define.

3. In argparse, how is an optional argument distinguished from a positional one?

  • A. By its type
  • B. By its position in the code
  • C. Its name starts with - or --
  • D. By a required=False flag only
Show answer

C. A name without dashes is positional and must be given.

Interview questions

What is the difference between sys.argv and argparse?

Show answer

sys.argv is the raw list of strings from the command line, with the script name first; everything else is up to you. argparse is built on top of it: you declare the arguments, and it parses them, converts types, applies defaults, rejects invalid input with a clear message and generates help text. sys.argv is enough for one simple argument; argparse is used for anything more.

How would you add a flag such as --verbose that takes no value?

Show answer

Declare it with action="store_true": parser.add_argument("--verbose", action="store_true"). The attribute is False by default and becomes True when the flag is present on the command line.

Key Points to Remember

  • sys.argv is a list of strings; argv[0] is the script name.
  • argparse adds types, defaults, choices, flags, nargs and automatic --help.
  • Invalid arguments exit with code 2 and a helpful message.
  • Sub-parsers create multi-command tools; Typer and Click are popular alternatives.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

Try Sub-commands like git in Webnest Codelab

These examples need a project environment on your computer, so they can be copied but not run here. Codelab runs Python, FastAPI backends with SQLite, plain Java 17 and HTML/CSS/JavaScript.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering