PYTHON MINI PROJECTS / PRACTICE 02
实战篇 2 · 写出靠谱的代码PRACTICE 02 · 调试 / 注解 / 命令行 / 批处理
目标:报错会读、调试有招、注解写清、路径不拼、参数能传、CSV/JSON 会批处理。
本章内容与知识点
第二份实战的主题是写出靠谱的代码:报错会倒着读 Traceback,调试有三板斧,类型注解把函数签名写清楚,pathlib 不再手拼路径,argparse 让脚本能带参数,CSV / JSON 会批处理。
排错
Traceback 倒着读调试三板斧
规范
类型注解PEP 8文档字符串
路径与参数
pathlibargparse
数据处理
CSV 读写JSON 批处理
本篇章知识点覆盖对照
| 知识点 | 落在哪个项目 | 你要做到的程度 |
|---|---|---|
| Traceback 倒着读 | 任务 1 | 会定位最后一行错误与自己的代码行 |
| 调试三板斧 | 任务 1 | 打印、logging.debug、breakpoint 各试一次 |
| 类型注解 list[str] / dict / | None | 案例、任务 2 | 会写函数注解并打印 __annotations__ |
| pathlib | 案例、任务 3 | 会用 open/write_text/mkdir/resolve |
| argparse | 案例、任务 3 | 会加必填参数与 --help |
| CSV 读写 | 任务 4 | 会用 DictWriter / DictReader |
| JSON 批处理 | 案例、任务 4 | 会"读一堆、汇一份" |
| 小项目该长什么样 | 案例 | 有入口、有函数、有注解、有错误处理 |
案例
小项目骨架(跟着敲)
介绍 · 完整可运行结构建一个 mini_project 目录,里面只放一个 main.py。它演示了"一个小项目该长什么样"。
# -*- coding: utf-8 -*-
"""实战 2 速览:类型注解 + pathlib + argparse + JSON。"""
import argparse
import json
from pathlib import Path
def load(path: Path) -> list[dict]:
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else []
def save(path: Path, data: list[dict]) -> None:
path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
parser = argparse.ArgumentParser(description="名字记录器")
parser.add_argument("name")
args = parser.parse_args()
p = Path("data.json")
data = load(p)
data.append({"name": args.name})
save(p, data)
print("已写入:", p.name, "共", len(data), "条")
cd mini_project python main.py 小明 python main.py 小红 python main.py --help
已写入: data.json 共 1 条 已写入: data.json 共 2 条 (--help 会打印参数说明,自己试一下)
- 两次运行会往同一个
data.json追加记录,所以第二次显示"共 2 条"。 - 看
--help自动生成的帮助,这就是 argparse 的好处。 - 把函数名、参数名都按 PEP 8 写,注解写清"收什么、返回什么"。
任务 1
Traceback 倒着读 + 调试三板斧
自己敲 · 打印 / 日志 / 断点解题提示:本题主要用到 打印、日志、断点。先对照要求自己敲一遍,卡住了再展开答案。
写 debug_lab.py,故意制造错误:
- 写
divide(a, b)返回a / b,调用divide(1, 0),运行后从最后一行倒着读 Traceback,找出错误类型和出错行。 - 第一板斧:在出错前加
print("调试:a=", a, "b=", b)。 - 第二板斧:改用
logging.debug(...)并配置 basicConfig。 - 第三板斧:在调用前加
breakpoint(),运行后用p b看变量、c继续、q退出。 - 注释写下:Traceback 最后一行才是真正的错误原因,上面的都是"调用路径"。
参考答案(先自己敲,再看)
# debug_lab.py —— 调试三板斧
import logging
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
def divide(a, b):
print("调试打印: a =", a, "b =", b) # 第一板斧
logging.debug("进入 divide,b=%s", b) # 第二板斧
return a / b
breakpoint() # 第三板斧:p b / c / q
result = divide(1, 0)
print(result)Traceback (most recent call last):
File "debug_lab.py", line 9, in <module>
result = divide(1, 0)
File "debug_lab.py", line 7, in divide
return a / b
ZeroDivisionError: division by zero读法:先跳到最后一行 ZeroDivisionError: division by zero,知道"除零了";再往上看第一处你自己写的文件和行号 line 7,那就是要改的地方。
任务 2
类型注解:把收什么、返回什么写清
自己敲 · list[str] / dict[str,int] / str | None解题提示:本题主要用到 list[str]、dict[str、int]、str | None。先对照要求自己敲一遍,卡住了再展开答案。
写 typing_lab.py:
- 写函数
greet(name: str, times: int = 1) -> str,返回重复 times 次的问候语。 - 写变量注解
names: list[str] = ["A","B"]、scores: dict[str, int] = {"A": 90}。 - 写
maybe: str | None = None,再用 if 判断后打印。 - 打印
greet.__annotations__查看注解对象。 - 注释说明:注解不强制类型,但 FastAPI 会用它做参数校验和文档生成。
参考答案(先自己敲,再看)
# typing_lab.py —— 类型注解
def greet(name: str, times: int = 1) -> str:
return (f"你好,{name}!\n" * times).strip()
names: list[str] = ["小明", "小红"]
scores: dict[str, int] = {"小明": 90, "小红": 95}
maybe: str | None = None
for n in names:
print(greet(n, 2))
print("分数:", scores)
if maybe is not None:
print(maybe.upper())
print("greet 的注解:", greet.__annotations__)
# 注解只是提示,不会强制检查;但 FastAPI 会拿它做请求校验和接口文档。你好,小明!
你好,小明!
你好,小红!
你好,小红!
分数: {'小明': 90, '小红': 95}
greet 的注解: {'name': <class 'str'>, 'times': <class 'int'>, 'return': <class 'str'>}任务 3
pathlib + argparse 让脚本能带参数跑
自己敲 · 路径对象 / 命令行参数解题提示:本题主要用到 路径对象、命令行参数。先对照要求自己敲一遍,卡住了再展开答案。
写 make_report.py:
- 用 argparse 接
-n/--name(必填)和-o/--output(默认report.txt)。 - 把
--output用type=Path直接转成路径对象。 - 用
output.parent.mkdir(parents=True, exist_ok=True)自动建父目录。 - 用
output.write_text(..., encoding="utf-8")写内容。 - 运行
python make_report.py -n 小明 -o out/report.txt,确认文件生成。
参考答案(先自己敲,再看)
# make_report.py —— pathlib + argparse
import argparse
from pathlib import Path
def main() -> None:
parser = argparse.ArgumentParser(description="生成简单报告")
parser.add_argument("-n", "--name", required=True, help="名字")
parser.add_argument("-o", "--output", type=Path, default=Path("report.txt"))
args = parser.parse_args()
args.output.parent.mkdir(parents=True, exist_ok=True)
content = f"报告\n姓名:{args.name}\n"
args.output.write_text(content, encoding="utf-8")
print("已写入:", args.output.resolve())
if __name__ == "__main__":
main()python make_report.py -n 小明 -o out/report.txt python make_report.py --help
任务 4
CSV 与 JSON 批处理
自己敲 · csv.DictWriter / DictReader / 汇总解题提示:本题主要用到 csv.DictWriter、DictReader、汇总。先对照要求自己敲一遍,卡住了再展开答案。
写 batch_io.py:
- 用
csv.DictWriter写 3 行学生数据到students.csv,编码用utf-8-sig(Excel 打开中文不乱码)。 - 用
csv.DictReader读回来,打印每行。 - 转成
{"姓名": 分数}的字典,用json.dump汇总到summary.json。 - 读回 summary.json 验证内容一致。
- 注释说明:csv 适合表格,json 适合嵌套结构,二者常配合做数据搬运。
参考答案(先自己敲,再看)
# batch_io.py —— CSV 与 JSON 批处理
import csv
import json
from pathlib import Path
rows = [
{"name": "小明", "score": "88"},
{"name": "小红", "score": "95"},
{"name": "小刚", "score": "72"},
]
with open("students.csv", "w", newline="", encoding="utf-8-sig") as f:
writer = csv.DictWriter(f, fieldnames=["name", "score"])
writer.writeheader()
writer.writerows(rows)
summary = {}
with open("students.csv", "r", newline="", encoding="utf-8-sig") as f:
for row in csv.DictReader(f):
print("读到:", row)
summary[row["name"]] = int(row["score"])
Path("summary.json").write_text(
json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8"
)
print("汇总:", json.loads(Path("summary.json").read_text(encoding="utf-8")))
# csv 适合表格数据,json 适合嵌套结构;批处理常见套路就是"读一堆、汇一份"。读到: {'name': '小明', 'score': '88'}
读到: {'name': '小红', 'score': '95'}
读到: {'name': '小刚', 'score': '72'}
汇总: {'小明': 88, '小红': 95, '小刚': 72}任务 5
类型注解写清楚
自己敲 · 类型注解 / list / dict解题提示:本题主要用到 类型注解、list[str]、dict。先对照要求自己敲一遍,卡住了再展开答案。
给函数加上类型注解,把"收什么、返回什么"写清楚,并打印注解信息。
- 定义
def total(prices: list[float]) -> float:,返回sum(prices)。 - 定义变量
scores: dict[str, int] = {"小明": 88}。 - 用
total.__annotations__打印函数的注解。 - 调用
total([1.5, 2.5])打印结果。
提示:注解只是提示,不会强制类型;但能让读代码的人和工具(如 mypy)看懂意图。
参考答案(先自己敲,再看)
# 类型注解写清楚
def total(prices: list[float]) -> float:
return sum(prices)
scores: dict[str, int] = {"小明": 88}
print("函数注解:", total.__annotations__)
print("调用结果:", total([1.5, 2.5]))
print("scores:", scores)函数注解: {'prices': list[float], 'return': <class 'float'>}
调用结果: 4.0
scores: {'小明': 88}