Sub topic 8
A minimal command-line interface
This chapter assumes you have the check-in, streak, completion-rate and JSON functions from the earlier chapters, and that you know basic argparse usage. Here you connect those functions to two commands, check and show, so you can run the tracker from a terminal.
Why a CLI
A habit tracker only works if logging takes seconds. Typing python habit.py check read is faster than opening a script, editing a line and running it. A command-line interface (CLI) also keeps the logic separate from the input handling. The functions you already wrote stay unchanged, and the CLI only decides which of them to call.
The flow of one command
Every run follows the same steps: load the data, do one action, save if something changed.
Only check writes to the file. show is read-only, so running it can never damage your data.
The full script
Save this as habit.py. It includes the functions from earlier chapters so the file runs on its own.
import argparse
import json
import sys
from datetime import date, timedelta
from pathlib import Path
PATH = "habits.json"
def save(log, path=PATH):
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=PATH):
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 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 build_parser():
parser = argparse.ArgumentParser(prog="habit")
sub = parser.add_subparsers(dest="command", required=True)
check = sub.add_parser("check", help="log today for a habit")
check.add_argument("habit")
show = sub.add_parser("show", help="show streaks and completion rate")
show.add_argument("habit")
return parser
def main(argv=None):
args = build_parser().parse_args(argv)
log = load()
today = date.today()
if args.command == "check":
log.setdefault(args.habit, set()).add(today)
save(log)
print(f"Logged '{args.habit}' for {today.isoformat()}")
return 0
days = log.get(args.habit)
if not days:
print(f"No check-ins yet for '{args.habit}'", file=sys.stderr)
return 1
print(f"Habit: {args.habit}")
print(f"Current streak: {current_streak(days, today)} days")
print(f"Longest streak: {longest_streak(days)} days")
print(f"Last 30 days: {completion_rate(days, today):.0%}")
return 0
if __name__ == "__main__":
sys.exit(main())Try it:
python habit.py check read
python habit.py check read
python habit.py show readThe second check changes nothing, because the log stores dates in a set. The output of show looks like this:
Habit: read
Current streak: 1 days
Longest streak: 1 days
Last 30 days: 3%How the pieces fit
- Subparsers.
add_subparsers(dest="command", required=True)makescheckandshowseparate commands, each with its own arguments. Settingrequired=Truemakes a barepython habit.pyprint a usage message instead of failing later with a confusing error. main(argv=None). Passingargvlets you test the CLI without a terminal, for examplemain(["show", "read"]). WhenargvisNone,argparsereadssys.argv.- Exit codes.
mainreturns0on success and1when the habit has no data.sys.exit(main())passes that value to the shell, so scripts can detect failure. - Error output. The "no check-ins" message goes to
stderr, which keeps normal output clean if someone pipesshowinto another program.
Common errors
| Symptom | Likely cause |
|---|---|
| `error: the following arguments are required: habit` | You ran `check` or `show` without a habit name. |
| `show` reports no check-ins right after `check` | You ran the two commands in different folders, so they used different `habits.json` files. |
| Habit names split into two entries | Habit names with spaces need quotes, as in `check "read book"`. Capitalization also matters: `Read` and `read` are different habits. |
| `ValueError` when loading | `habits.json` was edited by hand and contains a date that is not in `YYYY-MM-DD` form. |
Exercise
Add a list subcommand that prints every habit name with its current streak, one per line, sorted by name. Which two places in the script do you change, and does the command write to the file?
Show answer
First, add sub.add_parser("list", help="list all habits") in build_parser. Second, add a branch in main before the show code: if args.command == "list": for name in sorted(log): print(f"{name}: {current_streak(log[name], today)} days"); return 0. The command does not write to the file, so it must not call save. It needs no extra argument because it works on every habit in the log.