Sub topic 8
A minimal command-line interface
The earlier chapters gave you functions that record check-ins, compute streaks and completion rates, and save the log to JSON. This chapter wraps those functions in a command-line tool, so you can type python habit.py check read instead of editing code. The tool has two commands, check and show.
This chapter assumes you can read the functions from the previous chapters and know the basics of argparse, such as add_argument and positional arguments. It also assumes you can run a Python script from a terminal.
What the interface has to do
The interface does no habit logic of its own. It turns a line of text into a function call, and it turns the result into output and an exit code.
Keeping the interface thin has a practical benefit. The streak functions never see a string from the terminal, so you can test them without a terminal. The parser can change without touching them.
Designing the commands
Two commands are enough for a first version:
| Command | Arguments | Effect |
|---|---|---|
| `check` | habit name, optional `--date` | Logs a day (default: today) and saves |
| `show` | habit name | Prints current streak, longest streak and 30-day completion rate |
One option applies to every command: --file, the path of the JSON data file. It defaults to habits.json. It exists mainly so tests can use a temporary file instead of your real data.
Run show on a habit that has no check-ins to see what the exit code does. The command cannot show anything, so it prints a message to standard error and returns exit code 1. Scripts and shells use that code to detect failure.
The parser
Here is build_parser. It is the argparse snippet from the plan, extended with a shared option and a handler for each subcommand.
def build_parser():
parser = argparse.ArgumentParser(prog="habit")
parser.add_argument(
"--file", type=Path, default=DATA_FILE,
help="path to the JSON data file (default: habits.json)",
)
sub = parser.add_subparsers(dest="command", required=True)
check = sub.add_parser("check", help="log a day for a habit")
check.add_argument("habit")
check.add_argument(
"--date", type=date.fromisoformat, default=None,
help="day to log as YYYY-MM-DD (default: today)",
)
check.set_defaults(func=cmd_check)
show = sub.add_parser("show", help="show streaks and completion rate")
show.add_argument("habit")
show.set_defaults(func=cmd_show)
return parserFour details do most of the work:
required=Truemakes a missing subcommand an error. Without it, runninghabitalone leavesargs.commandasNoneand the program crashes later with a confusing message.dest="command"names the attribute that holds the chosen subcommand. It also lets error messages name the argument.type=date.fromisoformatconverts the text to adateduring parsing. If the text is not a valid ISO date,argparseprints a usage error and exits with code 2. Your handler never receives a bad date.set_defaults(func=...)attaches the handler to each subparser. The program then dispatches withargs.func(args)and needs noif/elifchain, which would grow with every new command.
--file is defined on the main parser, so it must come before the subcommand: habit --file other.json show read. Placing it after the subcommand fails, because the show subparser does not know that option.
The handlers
Each handler takes the parsed args, does one job and returns an exit code.
def cmd_check(args):
log = load(args.file)
day = args.date or date.today()
already = day in log.get(args.habit, set())
check_in(log, args.habit, day)
save(log, args.file)
if already:
print(f"{args.habit}: {day} was already logged.")
else:
print(f"{args.habit}: logged {day}.")
return 0
def cmd_show(args):
log = load(args.file)
days = log.get(args.habit)
if not days:
print(f"No check-ins for '{args.habit}'.", file=sys.stderr)
return 1
today = date.today()
print(args.habit)
print(f" current streak: {current_streak(days, today)}")
print(f" longest streak: {longest_streak(days)}")
print(f" last 30 days: {completion_rate(days, today):.0%}")
return 0cmd_check tells you when a day was already logged. This is the set from the data-model chapter doing its job. The duplicate add changes nothing, but the user should still know that nothing new happened. cmd_show checks if not days, which covers both a missing habit and an empty set. It writes the error to standard error so that normal output, which another program might read, stays clean.
The complete program
Here is the whole file. Save it as habit.py. The tracker functions are the ones from earlier chapters. check_in now takes the log as a parameter instead of using a global, because the handlers load the log fresh on each run.
import argparse
import json
import sys
from datetime import date, timedelta
from pathlib import Path
DATA_FILE = Path("habits.json")
def save(log, path=DATA_FILE):
data = {name: sorted(d.isoformat() for d in days) for name, days in log.items()}
Path(path).write_text(json.dumps(data, indent=2))
def load(path=DATA_FILE):
p = Path(path)
if not p.exists():
return {}
data = json.loads(p.read_text())
return {name: {date.fromisoformat(s) for s in days} for name, days in data.items()}
def check_in(log, habit, day=None):
day = day or date.today()
log.setdefault(habit, set()).add(day)
def current_streak(days, today=None):
today = today or date.today()
day = today if today in days else today - timedelta(days=1)
streak = 0
while day in days:
streak += 1
day -= timedelta(days=1)
return streak
def longest_streak(days):
best = run = 0
previous = None
for day in sorted(days):
if previous is not None and day - previous == timedelta(days=1):
run += 1
else:
run = 1
best = max(best, run)
previous = day
return best
def completion_rate(days, end, window=30):
start = end - timedelta(days=window - 1)
done = sum(1 for d in days if start <= d <= end)
return done / window
def cmd_check(args):
log = load(args.file)
day = args.date or date.today()
already = day in log.get(args.habit, set())
check_in(log, args.habit, day)
save(log, args.file)
if already:
print(f"{args.habit}: {day} was already logged.")
else:
print(f"{args.habit}: logged {day}.")
return 0
def cmd_show(args):
log = load(args.file)
days = log.get(args.habit)
if not days:
print(f"No check-ins for '{args.habit}'.", file=sys.stderr)
return 1
today = date.today()
print(args.habit)
print(f" current streak: {current_streak(days, today)}")
print(f" longest streak: {longest_streak(days)}")
print(f" last 30 days: {completion_rate(days, today):.0%}")
return 0
def build_parser():
parser = argparse.ArgumentParser(prog="habit")
parser.add_argument(
"--file", type=Path, default=DATA_FILE,
help="path to the JSON data file (default: habits.json)",
)
sub = parser.add_subparsers(dest="command", required=True)
check = sub.add_parser("check", help="log a day for a habit")
check.add_argument("habit")
check.add_argument(
"--date", type=date.fromisoformat, default=None,
help="day to log as YYYY-MM-DD (default: today)",
)
check.set_defaults(func=cmd_check)
show = sub.add_parser("show", help="show streaks and completion rate")
show.add_argument("habit")
show.set_defaults(func=cmd_show)
return parser
def main(argv=None):
args = build_parser().parse_args(argv)
return args.func(args)
if __name__ == "__main__":
sys.exit(main())Two structural choices are worth noting.
maintakesargv.parse_args(None)readssys.argv, so the command line works as usual. A test can pass a list instead.- The script ends with
sys.exit(main()). The handler's return value becomes the process exit code. Theif __name__ == "__main__"guard lets other files importhabitwithout running the interface.
Trying it
Run these commands in a terminal. The dates will be today's date on your machine.
$ python habit.py check read
read: logged 2026-11-27.
$ python habit.py check read
read: 2026-11-27 was already logged.
$ python habit.py show read
read
current streak: 1
longest streak: 1
last 30 days: 3%
$ python habit.py show swim
No check-ins for 'swim'.The 3% comes from one logged day in a 30-day window, which is 1/30, or 3.3%. The last command exits with code 1. In a POSIX shell, echo $? right afterwards prints it.
The --date option lets you backfill a day you forgot:
$ python habit.py check read --date 2026-11-26
read: logged 2026-11-26.A malformed date such as --date 26/11/2026 is rejected by the parser with a usage message and exit code 2. No handler runs and the data file is untouched.
Testing without a terminal
Because main accepts a list, you can call it directly. This script drives the real code against a temporary file, so it never touches your habits.json.
import tempfile
from pathlib import Path
import habit
with tempfile.TemporaryDirectory() as tmp:
data = str(Path(tmp) / "habits.json")
assert habit.main(["--file", data, "check", "read"]) == 0
assert habit.main(["--file", data, "show", "read"]) == 0
assert habit.main(["--file", data, "show", "swim"]) == 1
print("all checks passed")Invalid input behaves differently. argparse reports errors by raising SystemExit with code 2, so a test of a bad date needs try/except SystemExit, or pytest.raises(SystemExit) if you use pytest.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `AttributeError: 'Namespace' object has no attribute 'func'` | A subparser has no `set_defaults(func=...)` | Add the handler for every subcommand |
| `unrecognized arguments: --file ...` | `--file` placed after the subcommand | Put it before: `habit --file x.json show read` |
| Streak resets or data seems lost between runs | The handler forgot to call `save` | Call `save` after every change to the log |
| Crash on a hand-edited `habits.json` | `load` meets a malformed date string | Fix the file. Chapter 9 covers defensive handling |
| Different data from different folders | `habits.json` is relative to the current directory | Pass `--file` with an absolute path, or choose a fixed location |
Extending the interface
Adding a command takes three steps. Write a handler that takes args and returns an exit code. Register a subparser with its arguments. Attach the handler with set_defaults(func=...). Nothing in main changes. A list command that prints every habit name would be about five lines.
The interface still has gaps that later chapters address. The program calls date.today() inside the handler, so tests cannot fix the date. Chapter 9 deals with today, gaps and duplicates, and chapter 11 with non-daily schedules.
Exercise
Why does habit show read --file other.json fail, and what two changes would make it work either way?
Show answer
--file is defined on the main parser, so argparse only accepts it before the subcommand name. Once parsing enters the show subparser, that subparser does not know --file and reports an unrecognized argument. Either write habit --file other.json show read, or add --file to each subparser (for example with a shared parent parser passed through parents=[...]), taking care that its default does not overwrite a value given before the subcommand.
Exercise
Add a list command that prints each habit name with its number of check-ins, one per line, sorted by name. Which parts of the program change?
Show answer
Add a handler and register it. The handler is def cmd_list(args): log = load(args.file); [print(f"{name}: {len(days)}") for name, days in sorted(log.items())]; return 0, written with an ordinary for loop. The registration is sub.add_parser("list", help="list habits").set_defaults(func=cmd_list) inside build_parser. No other function changes, because main dispatches through args.func.
Exercise
A user runs python habit.py check read --date 2026-02-30. What happens, and does the data file change?
Show answer
February 30 is not a real date, so date.fromisoformat raises ValueError while argparse converts the argument. argparse turns that into a usage error on standard error and exits with code 2. cmd_check never runs, so load and save are never called and the file is unchanged.