Debug Python PDF generation errors by using unbuffered output and stderr inspection to reveal actual tracebacks
复制下面这句话,粘贴给 Claude Code、Codex、Cursor 等 AI 编程工具,它会读取安装说明并在你确认后完成安装。
请阅读 https://ai.atlankj.com/install/asset/gh-pdf-debug-unbuffered-73470f5744d6 ,按照其中的说明把「pdf-debug-unbuffered」安装到你(当前 AI 工具)中。执行前先告诉我将运行的命令和写入的位置,等我确认。
查看 AI 将读取的安装说明正在读取 GitHub 原文…
内容来自 GitHub 原始文件,由原作者维护。在 GitHub 查看
When Python PDF libraries (reportlab, fpdf, etc.) fail with generic "unknown error" messages, the actual cause is often hidden due to output buffering or error swallowing. This skill provides a technique to expose the real traceback.
Run the Python script with the -u flag (unbuffered output) and pipe stderr through head to capture the actual error:
python -u your_script.py 2>&1 | head -100
Or more specifically, to focus on stderr:
python -u your_script.py 2>&1 | head -50
-u flag: Forces Python to run in unbuffered mode, ensuring output (including errors) is flushed immediately rather than held in buffers that may be lost on crash2>&1: Redirects stderr to stdout so both streams are captured togetherhead: Limits output to show the most relevant error messages at the topLocate the Python script that generates the PDF and is producing generic errors.
python -u generate_pdf.py 2>&1 | head -100
Look for:
Address the specific error revealed in the traceback.
Once fixed, run the script without the debug flags to confirm it works:
python generate_pdf.py
| Symptom | Likely Cause |
|---|---|
| "unknown error" on PDF save | File path doesn't exist or no write permissions |
| Generic failure during build | Missing font files or font registration issues |
| Silent crash | ImportError for missing dependencies |
| Incomplete PDF | Script terminated early due to unhandled exception |
If the above doesn't work, try:
# Capture full stderr to a file
python -u script.py 2> error.log
# Use Python's traceback module explicitly
python -c "import traceback; exec(open('script.py').read())" 2>&1
# Run with verbose import tracing
python -v -u script.py 2>&1 | head -200
# Before: Generic error
python create_checklist.py
# Output: "Error: unknown"
# After: Actual traceback
python -u create_checklist.py 2>&1 | head -50
# Output: "FileNotFoundError: [Errno 2] No such file or directory: '/fonts/Helvetica.ttf'"
-u flag is available in Python 2.7+ and all Python 3 versionshead