Course topics

By WebNest Studio

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.

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.

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 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

Use your local project environment for these examples. Codelab currently runs Python and HTML/CSS/JavaScript; framework examples may need project dependencies.