Editor

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 lesson

Create 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: shopping
import argparse
# Build a subcommand CLI for notes

More argparse exercises

All Python exercises · 50 practice problems · Advanced Python quiz