Build a Subcommand CLI
Intermediate · Write the code · from Build Command-Line Tools with argparse and sys.argv
From the lesson: Build Command-Line Tools with argparse and sys.argv
Most Python scripts you've written so far run the same way every time. But what if you want the user to choose what your script does? That's where command-line arguments come in. Instead of hardcoding values, you let users pass them when they run your script.
Read the lessonCreate a note-taking CLI with two subcommands:
1. add subcommand with a positional text argument and optional --tag (default: 'general')
2. show subcommand with an optional --count argument of type=int (default: 5)
Parse ['add', 'Buy milk', '--tag', 'shopping'] and print:
Command: add
Text: Buy milk
Tag: shoppingimport argparse
# Build a subcommand CLI for notes
More argparse exercises
- Parse sys.argv ManuallyIntermediate
- Build a Basic argparse CLIIntermediate
- Type Validation and ChoicesIntermediate
- Fix the argparse BugIntermediate
All Python exercises · 50 practice problems · Advanced Python quiz