Files
admin ffef53c22f feat(项目十): 新增综合章节源码、章节正文与教材 docx
- textbook/main.c:单文件控制台程序(约 400 行、13 个函数),覆盖项目一~九知识点
- textbook/项目十-章节正文.md:章节正文源稿
- textbook/figs:8 张控制台运行结果截图(真实回显)
- textbook/tools:截图与 docx 生成脚本
- 10.16C语言程序设计教材初稿 - 项目十.docx:按原稿样式生成的综合章节(28 页)
2026-11-02 21:50:22 +08:00

141 lines
4.6 KiB
Python

"""Capture real console sessions, inject the typed keys at prompt positions,
crop to a readable window and render console-style screenshots."""
import os
import subprocess
import sys
from PIL import Image, ImageDraw, ImageFont
BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OUT = os.path.join(BASE, "figs")
FONT_PATH = r"C:\Windows\Fonts\simsun.ttc"
FONT_INDEX = 1
FONT_SIZE = 15
LINE_H = 21
PAD = 10
BG = (12, 12, 12)
FG = (212, 212, 212)
PROMPTS = [
"请选择功能(0-8):",
"请输入设备编号:",
"请选择操作:",
"请输入参数值:",
"请选择标志(1在线 2故障 3锁定 4节能):",
"请选择场景:",
]
def run(exe, inputs, cwd=BASE):
data = ("\n".join(inputs) + "\n").encode("utf-8")
p = subprocess.run([os.path.join(cwd, exe)], input=data,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd)
return p.stdout.decode("utf-8", "replace")
def inject(text, inputs):
out = []
i = 0
k = 0
while i < len(text):
hit = None
for p in PROMPTS:
if text.startswith(p, i):
hit = p
break
if hit is not None and k < len(inputs):
out.append(hit)
out.append(inputs[k] + "\r\n")
i += len(hit)
k += 1
else:
out.append(text[i])
i += 1
if k != len(inputs):
print(f" WARN: injected {k}/{len(inputs)} inputs", file=sys.stderr)
return "".join(out)
def window(lines, start_pat, end_pat, before=1, after=2):
i = next((n for n, l in enumerate(lines) if start_pat in l), None)
if i is None:
return lines
j = next((n for n in range(i, len(lines)) if end_pat in lines[n]), i)
return lines[max(0, i - before): j + after + 1]
def render(lines, path):
lines = [l.rstrip("\r") for l in lines]
while lines and not lines[-1].strip():
lines.pop()
while lines and not lines[0].strip():
lines.pop(0)
font = ImageFont.truetype(FONT_PATH, FONT_SIZE, index=FONT_INDEX)
width = max(int(font.getlength(l)) for l in lines) if lines else 400
w = max(width + 2 * PAD, 500)
h = len(lines) * LINE_H + 2 * PAD
img = Image.new("RGB", (w, h), BG)
d = ImageDraw.Draw(img)
for n, l in enumerate(lines):
d.text((PAD, PAD + n * LINE_H), l, font=font, fill=FG)
d.rectangle([0, 0, w - 1, h - 1], outline=(58, 58, 58))
img.save(path)
return len(lines), w, h
def fresh():
for f in ("devices.cfg", "smart_home.log"):
p = os.path.join(BASE, f)
if os.path.exists(p):
os.remove(p)
SPECS = {
"fig10-1": ("case10_1.exe", [], None),
"fig10-2": ("main.exe", ["1", "9", "0"], None),
"fig10-3": ("main.exe", ["2", "1", "3", "55", "2", "3", "3", "10", "0"], None),
"fig10-4": ("main.exe", ["3", "1", "1", "2", "3", "4", "5", "0"], None),
"fig10-5": ("main.exe", ["4", "3", "1", "0"], None),
"fig10-6": ("main.exe", ["5", "0"], None),
"fig10-8": ("main.exe", ["2", "1", "1", "3", "4", "4", "4", "3", "8", "0"],
("-------------------- 运行日志", "条记录", 2, 1)),
}
def main():
os.makedirs(OUT, exist_ok=True)
for name, (exe, inputs, crop) in SPECS.items():
fresh()
text = inject(run(exe, inputs), inputs)
lines = text.split("\n")
if crop:
lines = window(lines, crop[0], crop[1], crop[2], crop[3])
n, w, h = render(lines, os.path.join(OUT, name + ".png"))
with open(os.path.join(OUT, name + ".txt"), "w", encoding="utf-8") as f:
f.write("\n".join(lines))
print(f"{name}: lines={n} size=({w}x{h})")
# 图10-7: save+exit, restart, load+ledger
fresh()
t1 = inject(run("main.exe", ["6", "0"]), ["6", "0"])
l1 = window(t1.split("\n"), "==========", "保存成功", 0, 1)
t2 = inject(run("main.exe", ["7", "1", "0"]), ["7", "1", "0"])
l2 = window(t2.split("\n"), "加载成功", "共 6 台设备", 1, 1)
p1 = os.path.join(OUT, "fig10-7a.png")
p2 = os.path.join(OUT, "fig10-7b.png")
render(l1, p1)
render(l2, p2)
a, b = Image.open(p1), Image.open(p2)
w = max(a.width, b.width)
canvas = Image.new("RGB", (w, a.height + b.height + 14), (30, 30, 30))
canvas.paste(a, (0, 0))
canvas.paste(b, (0, a.height + 14))
canvas.save(os.path.join(OUT, "fig10-7.png"))
with open(os.path.join(OUT, "fig10-7.txt"), "w", encoding="utf-8") as f:
f.write("\n".join(l1) + "\n=== 重新启动 ===\n" + "\n".join(l2))
print(f"fig10-7: size=({canvas.width}x{canvas.height}) parts=({len(l1)},{len(l2)})")
if __name__ == "__main__":
main()