Handle code execution failures with fallback strategies and anchored workspace paths
复制下面这句话,粘贴给 Claude Code、Codex、Cursor 等 AI 编程工具,它会读取安装说明并在你确认后完成安装。
请阅读 https://ai.atlankj.com/install/asset/gh-code-execution-fallback-14b5b71c8289 ,按照其中的说明把「code-execution-fallback」安装到你(当前 AI 工具)中。执行前先告诉我将运行的命令和写入的位置,等我确认。
查看 AI 将读取的安装说明正在读取 GitHub 原文…
内容来自 GitHub 原始文件,由原作者维护。在 GitHub 查看
This skill provides a robust pattern for executing code when the primary method fails, combined with proper workspace path management to prevent file location errors.
Always establish and verify your working directory at the start of any task:
# At the beginning of any code execution
import os
workspace_path = os.getcwd()
print(f"Working directory: {workspace_path}")
# In shell scripts
pwd
echo "Current directory: $(pwd)"
Why: Prevents files from being written to unexpected locations when agents switch between tools.
When execute_code_sandbox fails, follow this escalation pattern:
run_shell with HeredocWhen sandbox execution repeatedly fails, switch to shell execution:
python3 << 'EOF'
import os
import pandas as pd
# Your code here
data = {"col1": [1, 2, 3], "col2": ["a", "b", "c"]}
df = pd.DataFrame(data)
df.to_csv("output.csv", index=False)
print("File written successfully")
EOF
Key points:
<< 'EOF' (quoted) to prevent variable expansionshell_agentFor complex multi-step tasks with error recovery needs:
Task: Create a data processing pipeline that reads CSV, transforms data, and outputs Excel
Requirements:
- Handle missing values
- Apply transformations
- Write to ./output/ directory
- Retry on transient errors
Always use absolute or explicitly relative paths:
# BAD - relies on implicit working directory
df.to_csv("output/data.csv")
# GOOD - explicit path anchoring
import os
base_path = os.getcwd()
output_dir = os.path.join(base_path, "output")
os.makedirs(output_dir, exist_ok=True)
df.to_csv(os.path.join(output_dir, "data.csv"))
# BAD
cd some_dir && python script.py
# GOOD
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"
python script.py
execute_code_sandbox fails?
├── Yes, with syntax/import errors → Fix code, retry Level 1
├── Yes, with timeout/resource errors → Use Level 2 (run_shell heredoc)
├── Yes, with unknown/unclear errors → Use Level 3 (shell_agent)
└── No, success → Verify output file exists at expected path
| Error Type | Likely Cause | Recommended Fallback |
|---|---|---|
| ModuleNotFoundError | Missing packages | run_shell with pip install first |
| Timeout | Long-running operation | shell_agent with progress tracking |
| PermissionError | Wrong directory | Verify workspace path, use explicit paths |
| Unknown error | Sandbox limitations | run_shell or shell_agent |
# Step 1: Anchor workspace
import os
workspace = os.getcwd()
print(f"Workspace: {workspace}")
# Step 2: Create output directory explicitly
output_path = os.path.join(workspace, "deliverables")
os.makedirs(output_path, exist_ok=True)
# Step 3: Generate content with error handling
try:
# Your generation logic here
with open(os.path.join(output_path, "report.txt"), "w") as f:
f.write("Content here")
print(f"Success: File written to {output_path}")
except Exception as e:
print(f"Error: {e}")
# Signal to escalate to run_shell or shell_agent
raise
../output/file.txt without contextexecute_code_sandbox without changing approachAfter any code execution: