Debug Python scripts with proper error surfacing and working directory verification
复制下面这句话,粘贴给 Claude Code、Codex、Cursor 等 AI 编程工具,它会读取安装说明并在你确认后完成安装。
请阅读 https://ai.atlankj.com/install/asset/gh-python-debug-execution-37185b49fce2 ,按照其中的说明把「python-debug-execution」安装到你(当前 AI 工具)中。执行前先告诉我将运行的命令和写入的位置,等我确认。
查看 AI 将读取的安装说明正在读取 GitHub 原文…
内容来自 GitHub 原始文件,由原作者维护。在 GitHub 查看
When executing Python scripts that may fail, use this pattern to surface clear error information and diagnose issues effectively.
Always run Python scripts with stderr redirected to stdout and echo the exit code:
python3 script.py 2>&1 ; echo Exit code: $?
Why this works:
2>&1 captures both stdout and stderr, ensuring tracebacks are visibleecho Exit code: $? reveals the actual exit status for debuggingBefore any file operations in Python scripts, add working directory verification:
import os
# At the start of your script or before file operations
print(f"Current working directory: {os.getcwd()}")
# For debugging, also list directory contents
print(f"Directory contents: {os.listdir('.')}")
Why this works:
#!/usr/bin/env python3
import os
import sys
def main():
# Diagnostic: verify execution context
print(f"Working directory: {os.getcwd()}")
print(f"Python version: {sys.version}")
print(f"Directory listing: {os.listdir('.')}")
# Your actual logic here
# ...
if __name__ == "__main__":
main()
python3 script.py 2>&1 ; echo Exit code: $?
Look for:
| Symptom | Likely Cause | Debug Clue |
|---|---|---|
| FileNotFoundError | Wrong working directory | Check os.getcwd() output |
| ModuleNotFoundError | Missing dependencies | Traceback shows import path |
| PermissionError | File access issues | Traceback shows file path |
| Silent failure (exit 0, no output) | Logic bug, not crash | Add print statements |