Use argparse to handle command-line arguments and flags
Structure a Python script for use as a command-line tool
Use sys.argv and stdin/stdout properly
Build subcommands like tool add, tool list, tool delete
💻 CLI Simulator — Task Manager
Simulate a command-line task manager. Type commands below to add, list, complete, and delete tasks.
$
Commands: task add "text" | task list | task done <id> | task delete <id> | task help
Why Build CLI Tools?
Command-line tools are the bread-and-butter of developer productivity. Git, npm, pip — all CLI tools. Python's argparse module makes it easy to build professional, self-documenting command-line interfaces with argument parsing, help text, and error messages built in.
argparse Basics
parser = argparse.ArgumentParser(description="...") — create the parser
parser.add_argument("--verbose", action="store_true") — optional flag
args = parser.parse_args() — parse sys.argv and return a Namespace object
Subcommands
Tools like git use subcommands: git add, git commit, git push. argparse supports this with add_subparsers(). Each subcommand gets its own parser and its own set of arguments.
Always include the if __name__ == "__main__": guard. This ensures the script only runs when executed directly, not when imported as a module.
Quick Check
1. What does argparse.ArgumentParser do when a required argument is missing?
Returns None for the missing argument
Prints an error message and usage info, then exits
Raises an AttributeError
Uses a default value of ""
2. What does action="store_true" do for an argument?
Stores the literal string "true"
Sets the argument to True if the flag is present, False if absent
Requires the user to pass true or false explicitly
Makes the argument required
3. Why use if __name__ == "__main__":?
It's required syntax for any Python script with argparse
It prevents the script's main code from running when the file is imported as a module
It defines the entry point for the Python interpreter
It makes the script run faster
4. How do subcommands work in argparse?
You define them in a separate configuration file
Use add_subparsers() and add_parser() to create a sub-parser for each subcommand
Each subcommand must be a separate Python file
argparse doesn't support subcommands — use sys.argv[1] instead