Day 14 · Todo CLI 完整版

Week 2 · Day 14 / 56 · 返回大纲

一、项目目标

整合 Week 1-2 所有知识,写出一个完整、可发布的 Todo CLI。

功能清单

命令功能
add "标题" [-p high]添加任务(可选优先级)
list [--all]列出任务
done <id>完成任务
delete <id>删除任务
edit <id> "新标题"修改任务
search "关键词"搜索任务
stats统计完成率
clear --yes清空所有任务

二、完整代码结构

todo_cli/
├── pyproject.toml    # 项目配置
├── todo/
│   ├── __init__.py
│   ├── cli.py        # 命令行入口
│   ├── storage.py    # 数据存储
│   └── models.py     # 数据模型(dataclass)
├── tests/
│   └── test_todo.py  # 测试
└── data.json         # 数据文件(自动生成)

三、数据模型(models.py)

from dataclasses import dataclass, asdict
from datetime import datetime

@dataclass
class Task:
    id: int
    title: str
    done: bool = False
    priority: str = "medium"
    created: str = ""
    
    def __post_init__(self):
        if not self.created:
            self.created = datetime.now().strftime("%Y-%m-%d")
    
    def to_dict(self) -> dict:
        return asdict(self)
    
    @classmethod
    def from_dict(cls, data: dict) -> "Task":
        return cls(**data)

四、存储模块(storage.py)

import json
from pathlib import Path
from models import Task

DATA_FILE = Path(__file__).parent.parent / "data.json"

def load() -> list[Task]:
    if not DATA_FILE.exists():
        return []
    try:
        data = json.loads(DATA_FILE.read_text(encoding="utf-8"))
        return [Task.from_dict(t) for t in data.get("tasks", [])]
    except (json.JSONDecodeError, KeyError):
        return []

def save(tasks: list[Task]):
    DATA_FILE.write_text(
        json.dumps({"tasks": [t.to_dict() for t in tasks]}, 
                   ensure_ascii=False, indent=2),
        encoding="utf-8"
    )

def add(title: str, priority: str = "medium") -> Task:
    tasks = load()
    task_id = max((t.id for t in tasks), default=0) + 1
    task = Task(id=task_id, title=title, priority=priority)
    tasks.append(task)
    save(tasks)
    return task

五、命令行(cli.py)

import argparse
from storage import load, save, add
from models import Task

def main():
    parser = argparse.ArgumentParser(description="Todo 任务管理器")
    sub = parser.add_subparsers(dest="cmd")

    # add
    p_add = sub.add_parser("add", help="添加任务")
    p_add.add_argument("title")
    p_add.add_argument("-p", "--priority", default="medium",
                       choices=["high", "medium", "low"])

    # list
    p_list = sub.add_parser("list", help="列出任务")
    p_list.add_argument("--all", action="store_true")

    # done
    p_done = sub.add_parser("done", help="完成任务")
    p_done.add_argument("id", type=int)

    # delete
    p_del = sub.add_parser("delete", help="删除任务")
    p_del.add_argument("id", type=int)

    # stats
    sub.add_parser("stats", help="统计")

    args = parser.parse_args()
    tasks = load()

    if args.cmd == "add":
        task = add(args.title, args.priority)
        print(f"✓ 添加:{task.title}(ID: {task.id})")
    
    elif args.cmd == "list":
        show = tasks if args.all else [t for t in tasks if not t.done]
        for t in show:
            icon = "✓" if t.done else "○"
            print(f"{icon} [{t.id}] {t.title} [{t.priority}]")
    
    elif args.cmd == "done":
        for t in tasks:
            if t.id == args.id:
                t.done = True
                save(tasks)
                print(f"✓ 完成 #{t.id}")
                return
        print(f"✗ 任务 #{args.id} 不存在")
    
    elif args.cmd == "delete":
        tasks = [t for t in tasks if t.id != args.id]
        save(tasks)
        print(f"✗ 已删除 #{args.id}")
    
    elif args.cmd == "stats":
        total = len(tasks)
        done = sum(1 for t in tasks if t.done)
        print(f"总计: {total}, 完成: {done}, 未完成: {total - done}")
        if total:
            print(f"完成率: {done/total*100:.1f}%")
    
    else:
        parser.print_help()

if __name__ == "__main__":
    main()

六、运行示例

$ python -m todo.cli add "学习 Python" -p high
✓ 添加:学习 Python(ID: 1)

$ python -m todo.cli add "写项目"
✓ 添加:写项目(ID: 2)

$ python -m todo.cli list
○ [1] 学习 Python [high]
○ [2] 写项目 [medium]

$ python -m todo.cli done 1
✓ 完成 #1

$ python -m todo.cli stats
总计: 2, 完成: 1, 未完成: 1
完成率: 50.0%

动手练习

练习 1:写测试
用 pytest 写 Todo 的测试
# tests/test_todo.py
from todo.storage import add, load

def test_add_task():
    task = add("测试任务")
    tasks = load()
    assert task in tasks

def test_list_only_pending():
    tasks = load()
    pending = [t for t in tasks if not t.done]
    assert all(not t.done for t in pending)
查看答案
参考答案
# 运行:uv run pytest
练习 2:导出 Markdown
把任务导出为 Markdown 格式
def export_markdown(tasks):
    lines = ["# Todo 任务清单\n"]
    for t in tasks:
        box = "[x]" if t.done else "[ ]"
        lines.append(f"- {box} {t.title}")
    return "\n".join(lines)
查看答案
参考答案
# 方便在 GitHub 或笔记中查看
练习 3:按优先级筛选
list 命令加 --high/--medium/--low 参数
# p_list.add_argument("-p", "--priority", 
#                     choices=["high", "medium", "low"])
# 过滤逻辑:
if args.priority:
    show = [t for t in show if t.priority == args.priority]
查看答案
参考答案
# 组合多个筛选条件

打卡验收

能写出完整的 Todo CLI 项目
理解模块拆分:cli/storage/models
会用 dataclass 定义数据模型
会用 argparse 定义完整的子命令
理解 JSON 数据持久化
完成 3 个扩展练习
项目可以正常运行,无报错
能向别人演示完整的项目
打卡方式: 全部勾选后,告诉我 "Day 14 打卡",并贴出你的代码。