"""Small, single-user example of a resumable local task."""
import argparse
import csv
from datetime import datetime, timezone
import json
from pathlib import Path
from tempfile import NamedTemporaryFile
def now():
return datetime.now(timezone.utc).isoformat()
def initial():
return {"phase": "collecting", "file": None, "goal": None, "result": None, "created_at": now()}
def save(path, state):
state["updated_at"] = now()
with NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n", dir=path.parent, delete=False) as handle:
temporary = Path(handle.name)
try:
json.dump(state, handle, ensure_ascii=False, indent=2)
except BaseException:
handle.close()
temporary.unlink()
raise
try:
temporary.replace(path)
finally:
temporary.unlink(missing_ok=True)
def choose(args):
for source in ("latest", "upload", "history", "default"):
value = getattr(args, source)
if value:
return {"source": source, "file": value}
return {"source": None, "file": None}
def summarize(path, goal):
with path.open(encoding="utf-8", newline="") as handle:
reader = csv.DictReader(handle)
if not reader.fieldnames or "units" not in reader.fieldnames:
raise ValueError("需要 units 列")
units = [int(row["units"]) for row in reader]
if not units:
raise ValueError("至少需要一行数据")
return {"rows": len(units), "goal": goal, "value": sum(units) if goal == "total" else max(units)}
def transition(args):
path = args.state
if args.action == "reset":
path.unlink(missing_ok=True)
return 0, {"phase": "collecting", "message": "已清除本次任务状态"}
state = json.loads(path.read_text(encoding="utf-8")) if path.exists() else initial()
if args.action == "status":
return 0, state
if args.action == "collect":
if not (args.file or args.goal):
return 2, {"error": "请输入文件路径或目标", "phase": state["phase"]}
state.update(phase="collecting", result=None)
if args.file:
state["file"] = str(args.file.resolve())
if args.goal:
state["goal"] = args.goal
if state["file"] and state["goal"]:
state["phase"] = "confirming"
save(path, state)
return 0, state
if args.action == "confirm" and state["phase"] == "confirming":
state["phase"] = "executing"
save(path, state)
return 0, {"phase": "executing", "message": "计划已确认,可运行"}
if args.action == "run" and state["phase"] == "done":
return 0, {"phase": "done", "result": state["result"], "reused": True}
if args.action == "run" and state["phase"] == "executing":
try:
result = summarize(Path(state["file"]), state["goal"])
except (OSError, ValueError, csv.Error):
return 3, {"phase": "executing", "error": "检查路径、UTF-8 编码和 units 列的数据"}
state.update(phase="done", result=result)
save(path, state)
return 0, {"phase": "done", "result": result, "reused": False}
return 2, {"phase": state["phase"], "error": "先收集完整信息并确认计划"}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--state", type=Path, default=Path("session.json"))
commands = parser.add_subparsers(dest="action", required=True)
collect = commands.add_parser("collect")
collect.add_argument("--file", type=Path)
collect.add_argument("--goal", choices=("total", "max"))
for action in ("status", "confirm", "run", "reset"):
commands.add_parser(action)
pick = commands.add_parser("choose")
for source in ("latest", "upload", "history", "default"):
pick.add_argument("--" + source)
args = parser.parse_args()
code, value = (0, choose(args)) if args.action == "choose" else transition(args)
print(json.dumps(value, ensure_ascii=False))
return code
if __name__ == "__main__":
raise SystemExit(main())
本例需在 Windows、Python 3.12。各实验所需工具和版本见下载包 README。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。
入口文件:projects/skills-context/state.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
state.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12。各实验所需工具和版本见下载包 README。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a331.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a333.zip