整合 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 # 数据文件(自动生成)
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)
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
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()
# 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
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 或笔记中查看
# p_list.add_argument("-p", "--priority",
# choices=["high", "medium", "low"])
# 过滤逻辑:
if args.priority:
show = [t for t in show if t.priority == args.priority]
# 组合多个筛选条件