任务管理系统(Task Management System)是一种用于创建、组织、跟踪和完成任务的软件工具,广泛应用于个人待办(To-Do)、团队协作(如敏捷开发)、项目管理等场景。一个基础但实用的任务管理系统应至少支持以下核心功能:
✅ 任务的增删改查(CRUD)
✅ 任务状态管理(如:待办 / 进行中 / 已完成 / 已取消)
✅ 优先级设置(如:低/中/高)
✅ 截止时间(deadline)与创建时间记录
✅ 持久化存储(如使用 JSON 文件模拟数据库,便于教学与轻量部署)
下面我将用 **Python + 命令行界面(CLI)** 实现一个简洁、可运行的本地任务管理系统(无外部依赖),并附详细解释。
---
### ✅ Python 实现:轻量级 CLI 任务管理系统
```python
import json
import os
from datetime import datetime
from typing import List, Dict, Optional
# 默认任务数据文件路径
TASKS_FILE = "tasks.json"
# 任务状态枚举(字符串模拟)
STATUS_OPTIONS = ["pending", "in-progress", "completed", "cancelled"]
PRIORITY_OPTIONS = ["low", "medium", "high"]
class Task:
def __init__(self, title: str, description: str = "", status: str = "pending",
priority: str = "medium", deadline: Optional[str] = None, task_id: Optional[int] = None):
self.id = task_id or self._generate_id()
self.title = title.strip()
self.description = description.strip()
self.status = status if status in STATUS_OPTIONS else "pending"
self.priority = priority if priority in PRIORITY_OPTIONS else "medium"
self.created_at = datetime.now().isoformat()
self.updated_at = self.created_at
self.deadline = deadline # ISO 格式字符串,如 "2025-12-31T23:59:59"
def _generate_id(self) -> int:
# 简单 ID 生成:取当前时间戳毫秒末4位 + 随机偏移(避免并发问题不重要,仅 CLI 场景)
return int(datetime.now().strftime("%f")) % 10000 + 1000
def to_dict(self) -> Dict:
return {
"id": self.id,
"title": self.title,
"description": self.description,
"status": self.status,
"priority": self.priority,
"created_at": self.created_at,
"updated_at": self.updated_at,
"deadline": self.deadline
}
@classmethod
def from_dict(cls, data: Dict) -> 'Task':
return cls(
title=data["title"],
description=data.get("description", ""),
status=data.get("status", "pending"),
priority=data.get("priority", "medium"),
deadline=data.get("deadline"),
task_id=data["id"]
)
class TaskManager:
def __init__(self, storage_file: str = TASKS_FILE):
self.storage_file = storage_file
self.tasks: List[Task] = self._load_tasks()
def _load_tasks(self) -> List[Task]:
if not os.path.exists(self.storage_file):
return []
try:
with open(self.storage_file, "r", encoding="utf-8") as f:
data = json.load(f)
return [Task.from_dict(item) for item in data]
except (json.JSONDecodeError, KeyError, TypeError):
print(f"⚠️ 警告:{self.storage_file} 格式错误,将初始化为空任务列表。")
return []
def _save_tasks(self):
data = [task.to_dict() for task in self.tasks]
with open(self.storage_file, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
def add_task(self, title: str, description: str = "", status: str = "pending",
priority: str = "medium", deadline: Optional[str] = None) -> Task:
task = Task(title, description, status, priority, deadline)
self.tasks.append(task)
self._save_tasks()
return task
def get_task(self, task_id: int) -> Optional[Task]:
return next((t for t in self.tasks if t.id == task_id), None)
def update_task(self, task_id: int, **kwargs) -> bool:
task = self.get_task(task_id)
if not task:
return False
allowed_fields = {"title", "description", "status", "priority", "deadline"}
for k, v in kwargs.items():
if k in allowed_fields and k != "id":
setattr(task, k, v.strip() if isinstance(v, str) else v)
task.updated_at = datetime.now().isoformat()
self._save_tasks()
return True
def delete_task(self, task_id: int) -> bool:
original_len = len(self.tasks)
self.tasks = [t for t in self.tasks if t.id != task_id]
if len(self.tasks) < original_len:
self._save_tasks()
return True
return False
def list_tasks(self, status: Optional[str] = None, priority: Optional[str] = None) -> List[Task]:
filtered = self.tasks
if status and status in STATUS_OPTIONS:
filtered = [t for t in filtered if t.status == status]
if priority and priority in PRIORITY_OPTIONS:
filtered = [t for t in filtered if t.priority == priority]
return sorted(filtered, key=lambda t: (t.priority != "high", t.created_at)) # high 优先 + 时间早优先
def search_tasks(self, keyword: str) -> List[Task]:
kw = keyword.lower()
return [
t for t in self.tasks
if kw in t.title.lower() or kw in t.description.lower()
]
# —————— CLI 交互层 ——————
def print_task(task: Task):
status_emoji = {"pending": "⏳", "in-progress": "🔧", "completed": "✅", "cancelled": "❌"}
priority_emoji = {"low": "🔽", "medium": "🔼", "high": "🔥"}
deadline_str = f"📅 {task.deadline[:10]}" if task.deadline else ""
print(f"[{task.id}] {status_emoji.get(task.status, '❓')} {task.title}")
if task.description:
print(f" 📝 {task.description}")
print(f" {priority_emoji.get(task.priority, '❓')} {task.priority.upper()} | "
f"⏱️ {task.created_at[:10]} | {deadline_str}")
print()
def main():
tm = TaskManager()
print("🎯 欢迎使用简易任务管理系统(CLI 版)")
print("输入 'help' 查看命令列表,'quit' 退出。\n")
while True:
try:
cmd = input("task> ").strip()
if not cmd:
continue
parts = cmd.split(maxsplit=1)
op = parts[0].lower()
args = parts[1] if len(parts) > 1 else ""
if op == "quit" or op == "exit":
print("👋 再见!任务已自动保存。")
break
elif op == "help":
print("""
可用命令:
add <title> [--desc <text>] [--status <s>] [--priority <p>] [--due <YYYY-MM-DD>]
list [--status pending|in-progress|completed|cancelled] [--priority low|medium|high]
show <id>
update <id> <field>=<value> ... (支持:title, description, status, priority, deadline)
delete <id>
search <keyword>
clear (清空所有任务,谨慎!)
help
quit
""".strip())
elif op == "add":
# 简单解析:支持 --desc "xxx" 等
import shlex
try:
tokens = shlex.split(cmd)
title = tokens[1] if len(tokens) > 1 else ""
if not title:
print("❌ 错误:add 至少需要标题。")
continue
kwargs = {"title": title}
i = 2
while i < len(tokens):
opt = tokens[i]
if opt == "--desc" and i+1 < len(tokens):
kwargs["description"] = tokens[i+1]
i += 2
elif opt == "--status" and i+1 < len(tokens) and tokens[i+1] in STATUS_OPTIONS:
kwargs["status"] = tokens[i+1]
i += 2
elif opt == "--priority" and i+1 < len(tokens) and tokens[i+1] in PRIORITY_OPTIONS:
kwargs["priority"] = tokens[i+1]
i += 2
elif opt == "--due" and i+1 < len(tokens):
due = tokens[i+1]
# 简单校验 YYYY-MM-DD 格式
if len(due) == 10 and due[4]=='-' and due[7]=='-':
kwargs["deadline"] = f"{due}T23:59:59"
else:
print(f"⚠️ 截止日期格式应为 YYYY-MM-DD,跳过。")
i += 2
else:
i += 1
tm.add_task(**kwargs)
print(f"✅ 已添加任务 #{kwargs['title']}")
except Exception as e:
print(f"❌ 添加失败:{e}")
elif op == "list":
status = None
priority = None
if "--status" in args:
status = args.split("--status", 1)[1].split()[0].strip() if "--status" in args else None
if "--priority" in args:
priority = args.split("--priority", 1)[1].split()[0].strip() if "--priority" in args else None
tasks = tm.list_tasks(status=status, priority=priority)
if not tasks:
print("📝 当前无任务。")
else:
print(f"📋 共 {len(tasks)} 个任务:")
for t in tasks:
print_task(t)
elif op == "show" and args.isdigit():
task = tm.get_task(int(args))
if task:
print_task(task)
else:
print("❌ 未找到该 ID 的任务。")
elif op == "update" and args:
try:
tid, *kv_pairs = args.split()
task_id = int(tid)
updates = {}
for kv in kv_pairs:
if "=" in kv:
k, v = kv.split("=", 1)
k = k.strip()
v = v.strip().strip('"\'')
if k in ["status", "priority"] and v not in (STATUS_OPTIONS + PRIORITY_OPTIONS):
print(f"⚠️ 忽略非法值:{k}={v}")
continue
updates[k] = v
if tm.update_task(task_id, **updates):
print(f"✅ 任务 #{task_id} 已更新。")
else:
print("❌ 更新失败:任务不存在。")
except ValueError:
print("❌ ID 必须是数字。")
except Exception as e:
print(f"❌ 更新出错:{e}")
elif op == "delete" and args.isdigit():
if tm.delete_task(int(args)):
print(f"🗑️ 已删除任务 #{args}")
else:
print("❌ 删除失败:任务不存在。")
elif op == "search":
if args:
results = tm.search_tasks(args)
if results:
print(f"🔍 搜索 '{args}' 共 {len(results)} 个结果:")
for t in results:
print_task(t)
else:
print("❌ 未匹配到任务。")
else:
print("❌ 请提供搜索关键词。")
elif op == "clear":
confirm = input("⚠️ 确认清空所有任务?(y/N): ").strip().lower()
if confirm in ("y", "yes", "是"):
tm.tasks = []
tm._save_tasks()
print("✅ 所有任务已清空。")
else:
print("❌ 已取消。")
else:
print(f"❌ 未知命令 '{op}'。输入 'help' 查看帮助。")
except KeyboardInterrupt:
print("\n👋 正在退出...")
break
except EOFError:
print("\n👋 再见!")
break
if __name__ == "__main__":
main()
```
---
### 🔍 代码解释说明:
1. **`Task` 类**
- 封装单个任务的数据结构,含 `id`, `title`, `status`, `priority`, `deadline`, 时间戳等字段;
- 提供 `to_dict()` / `from_dict()` 支持 JSON 序列化/反序列化;
- ID 使用毫秒随机生成(CLI 单用户场景足够唯一)。
2. **`TaskManager` 类**
- 负责任务的持久化(JSON 文件读写)、内存缓存、业务逻辑(增删改查、过滤、搜索);
- `list_tasks()` 支持按状态/优先级筛选,并按「高优优先 + 创建时间早」排序;
- `search_tasks()` 支持标题/描述模糊匹配(不区分大小写)。
3. **CLI 交互层**
- 支持类 Unix 命令风格(如 `add "开会" --priority high --due 2025-06-30`);
- 使用 `shlex.split()` 正确解析带空格/引号的参数(如 `--desc "准备PPT"`);
- 输入验证(日期格式、状态合法性、ID 数字性)提升鲁棒性;
- 所有变更实时写入 `tasks.json`,关机/崩溃也不丢数据。
4. **用户体验细节**
- Emoji 可视化状态与优先级(提升可读性);
- `clear` 命令二次确认防误操作;
- `help` 输出清晰命令文档;
- 异常捕获(JSON损坏、键盘中断等)保证程序不崩溃。
✅ 运行方式:保存为 `task_cli.py`,终端执行 `python task_cli.py` 即可开始使用。
✅ 数据自动保存在同目录 `tasks.json`,可直接用文本编辑器查看或备份。
---
### 🧩 扩展建议(进阶方向):
- ✅ 添加 Web 版本(Flask/FastAPI + HTML 前端)
- ✅ 支持子任务/任务分组/标签(tags)
- ✅ 集成通知(截止前提醒 via `schedule` 或系统托盘)
- ✅ 多用户支持(SQLite + 用户登录)
- ✅ 导出为 CSV / Markdown / iCal 日历
---