Skip to content

Command-Line Arguments and Building CLI Tools

Beginning of the lesson

Command-Line Arguments and Building CLI Tools

Turn a script into a real tool that reads options from the command line with argparse

Big Idea: A command-line tool is just a Python script that reads the words the user typed after the program name. The standard-library module argparse takes that raw list of words, checks it against the arguments you declared, converts each value to the right type, generates a help screen for free, and hands you a tidy object with your settings. You describe what the tool accepts; argparse does the parsing, validating and error-reporting for you.
By the end you will be able to:
  • read raw arguments from sys.argv and see why it is not enough,
  • declare positional arguments and optional flags with add_argument,
  • set default values, convert with type, and restrict with choices,
  • add on/off switches with action="store_true",
  • write good help text and read the auto-generated usage screen,
  • split a big tool into subcommands like add and list.

1. The raw material: sys.argv

When you run python greet.py Alice --loud, Python hands your program the words that followed it as a list of strings called sys.argv. The first item is always the script name; the rest are what the user typed.

import sys

# run as:  python greet.py Alice --loud
print(sys.argv)
# ['greet.py', 'Alice', '--loud']

You could parse that list by hand, but you would quickly be writing fragile code: checking lengths, hunting for --loud, converting "3" to an int, printing a help message, and reporting friendly errors when the user mistypes. Every serious tool needs the same plumbing, so the standard library ships it as argparse.

Notice that everything in sys.argv is a string, even "3". Converting and validating those strings is exactly the work argparse takes off your hands.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers