-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask_cli.py
More file actions
194 lines (152 loc) · 5.82 KB
/
task_cli.py
File metadata and controls
194 lines (152 loc) · 5.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
"""
Task Tracker CLI - 项目骨架
用法示例:
python task_cli.py add "买菜"
python task_cli.py list
python task_cli.py update 1 "买菜和做饭"
python task_cli.py mark-done 1
python task_cli.py delete 1
"""
import sys
import json
import os
from datetime import datetime
# 存储任务的文件名
TASKS_FILE = "tasks.json"
# ========== 核心工具函数 ==========
def load_tasks():
"""读取所有任务。如果文件不存在,返回空列表。"""
if not os.path.exists(TASKS_FILE):
return []
with open(TASKS_FILE, "r", encoding="utf-8") as f:
# 处理空文件的情况
content = f.read().strip()
if not content:
return []
return json.loads(content)
def save_tasks(tasks):
"""把任务列表写回文件。"""
with open(TASKS_FILE, "w", encoding="utf-8") as f:
json.dump(tasks, f, ensure_ascii=False, indent=2)
def now():
"""返回当前时间的 ISO 格式字符串。"""
return datetime.now().isoformat(timespec="seconds")
# ========== 命令实现函数 ==========
def add_task(description):
"""添加一个新任务。"""
tasks = load_tasks()
# TODO 1: 生成新 ID
# 提示: 找出 tasks 里最大的 id, 加 1; 如果列表是空的就用 1
new_id = max([t["id"] for t in tasks], default=0) + 1
# TODO 2: 构造新任务字典
# 需要的字段: id, description, status (初始为 "todo"), createdAt, updatedAt
new_task = {
"id":new_id,
"description":description,
"status":"todo",
"createdAt":now(),
"updatedAt":now()
} # ← 在这里实现
tasks.append(new_task)
save_tasks(tasks)
print(f"Task added successfully (ID: {new_id})")
def update_task(task_id, new_description):
"""更新指定 ID 任务的描述。"""
tasks = load_tasks()
# TODO 3: 遍历 tasks, 找到 id 匹配的那一个
# 找到了: 修改它的 description, 更新 updatedAt, 保存, 打印成功
# 没找到: 打印 "Task not found"
# 提示: 用 for 循环, 或者更优雅的写法 next((t for t in tasks if t["id"] == task_id), None)
task = next((t for t in tasks if t["id"] == task_id), None)
if task:
task["description"] = new_description
task["updatedAt"] = now()
save_tasks(tasks)
print("Task updated successfully")
else:
print("Task not found")
def delete_task(task_id):
"""删除指定 ID 的任务。"""
tasks = load_tasks()
# TODO 4: 从 tasks 中移除 id 匹配的任务
# 提示: 可以用列表推导 [t for t in tasks if t["id"] != task_id]
# 记得判断: 如果新列表长度和原来一样, 说明没找到, 提示用户
new_tasks = [t for t in tasks if t["id"] != task_id]
if len(new_tasks) == len(tasks):
print("Task not found")
else:
save_tasks(new_tasks)
print("Task deleted successfully")
def mark_task(task_id, new_status):
"""把任务标记为指定状态 (in-progress 或 done)。"""
tasks = load_tasks()
# TODO 5: 类似 update_task, 但改的是 status 字段
task = next((t for t in tasks if t["id"] == task_id), None)
if task:
task["status"] = new_status
task["updatedAt"] = now()
save_tasks(tasks)
print("Task status updated successfully")
else:
print("Task not found")
def list_tasks(filter_status=None):
"""列出任务。filter_status 为 None 时列出全部, 否则按状态过滤。"""
tasks = load_tasks()
# TODO 6: 如果 filter_status 不是 None, 只保留 status == filter_status 的任务
# 然后把每个任务打印出来 (id, description, status, 时间)
# 如果列表为空, 打印 "No tasks found"
filtered_tasks = [t for t in tasks if t["status"] == filter_status] if filter_status else tasks
if not filtered_tasks:
print("No tasks found")
return
for t in filtered_tasks:
print(f"ID: {t['id']}, Description: {t['description']}, Status: {t['status']}, Created At: {t['createdAt']}, Updated At: {t['updatedAt']}")
return
# ← 在这里实现
# ========== 命令分发 ==========
def main():
# sys.argv[0] 是脚本名, sys.argv[1] 是第一个真正的参数
args = sys.argv[1:]
if len(args) == 0:
print("Usage: python task_cli.py <command> [arguments]")
print("Commands: add, update, delete, list, mark-in-progress, mark-done")
return
command = args[0]
try:
if command == "add":
if len(args) < 2:
print("Error: please provide a task description")
return
add_task(args[1])
elif command == "update":
if len(args) < 3:
print("Error: usage: update <id> <new description>")
return
update_task(int(args[1]), args[2])
elif command == "delete":
if len(args) < 2:
print("Error: please provide a task ID")
return
delete_task(int(args[1]))
elif command == "mark-in-progress":
mark_task(int(args[1]), "in-progress")
elif command == "mark-done":
mark_task(int(args[1]), "done")
elif command == "list":
if len(args) == 1:
list_tasks()
else:
status = args[1]
# 题目里 "todo" 对应未完成, 注意这里要和你存的 status 值对应
if status not in ("todo", "in-progress", "done"):
print(f"Error: unknown status '{status}'")
return
list_tasks(status)
else:
print(f"Error: unknown command '{command}'")
except ValueError:
print("Error: ID must be a number")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()