python-execution-fallback
What it does
This skill gives the AI agent a clear order of steps when Python code fails to run. It is for people who need a reliable way to get Python code working through an AI.
When to use it
- ✓When inline Python code fails with a syntax or runtime error.
- ✓When heredoc code gives parsing problems and you need a more stable approach.
- ✓When a spreadsheet or data generation job fails when run inline.
Skill link
https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/python-execution-fallback/SKILL.mdCopy it and paste it into your AI (Claude, ChatGPT or Cursor), asking it to follow the instructions.
How to use
The easiest way: copy the message and paste it into your AI. It reads the skill and follows the instructions.
Ready-to-paste message
For Claude Code, Codex or Cursor: run it in your project folder and the skill gets installed.
Download the SKILL.md and drop it into your agent’s skills folder.
Example of what to ask your AI
“My Python code keeps failing when I run it inline. Save it as a script and run it, then check the results.”
5 new skills a week. 1 minute to read.
How it works
The agent first tries the code inline. If that fails, it saves the full script to a .py file, runs that file through the shell, and checks that the output is complete and correct.
Technical content (original SKILL.md)
Original text by the author, straight from GitHub.
Python Execution Fallback Workflow
This skill provides a systematic debugging approach when inline Python code execution fails, particularly in heredoc or shell_agent contexts.
Pattern Overview
When Python code execution fails, follow this recovery workflow:
- Attempt inline execution first - Try running Python code directly
- Write script to file on failure - Persist the code to a
.pyfile - Execute the file - Run the saved script via shell
- Validate output - Verify results are correct and complete
When to Use
Apply this pattern when:
- Inline Python execution fails with syntax or runtime errors
- Heredoc-based code execution encounters parsing issues
- Working with complex multi-line scripts that need debugging
- Need systematic approach to isolate execution failures
- Spreadsheet/data generation tasks fail in inline mode
Step-by-Step Instructions
Step 1: Attempt Inline Execution
Try executing Python code inline first (using execute_code_sandbox or similar):
# Example: Attempt inline execution
import pandas as pd
import openpyxl
df = pd.read_excel("input.xlsx")
# Process data...
df.to_excel("output.xlsx", index=False)
If this succeeds, proceed. If it fails, move to Step 2.
Step 2: Write Script to File (On Failure)
When inline execution fails, write the complete script to a persistent file:
# Capture the script content
script_content = '''
import pandas as pd
import openpyxl
import sys
try:
# Your original code here
df = pd.read_excel("input.xlsx")
# Processing logic
result_df = df.groupby("category").sum()
# Output
result_df.to_excel("output.xlsx", index=False)
print("SUCCESS: File generated")
except Exception as e:
print(f"ERROR: {e}", file=sys.stderr)
sys.exit(1)
'''
# Write to file
with open("script.py", "w") as f:
f.write(script_content)
print("Script written to script.py")
Step 3: Execute the File
Run the saved script using shell execution:
python script.py
Or with error capture:
python script.py 2>&1 | tee execution.log
This approach:
- Avoids heredoc parsing issues
- Provides clearer error messages
- Allows script inspection and modification
- Enables re-execution without rewriting
Step 4: Validate Output
Verify the results are correct:
# Validation script
import pandas as pd
import os
# Check file exists
if os.path.exists("output.xlsx"):
df = pd.read_excel("output.xlsx")
print(f"Rows: {len(df)}, Columns: {len(df.columns)}")
print(df.head())
print("VALIDATION: PASSED")
else:
print("VALIDATION: FAILED - Output file missing")
Code Example: Complete Workflow
# Full fallback workflow example
def generate_spreadsheet_fallback(data, output_path):
"""Generate spreadsheet with fallback workflow"""
# Step 1: Try inline
inline_script = f'''
import pandas as pd
data = {data}
df = pd.DataFrame(data)
df.to_excel("{output_path}", index=False)
'''
try:
# Attempt inline execution
result = execute_code_sandbox(code=inline_script)
if "error" not in result.lower():
return "SUCCESS_INLINE"
except Exception as e:
pass
# Step 2: Write to file
file_script = f'''
import pandas as pd
import sys
try:
data = {data}
df = pd.DataFrame(data)
df.to_excel("{output_path}", index=False)
print("SUCCESS")
except Exception as e:
print(f"ERROR: {{e}}", file=sys.stderr)
sys.exit(1)
'''
with open("generate.py", "w") as f:
f.write(file_script)
# Step 3: Execute file
shell_result = run_shell(command="python generate.py")
# Step 4: Validate
if os.path.exists(output_path):
return "SUCCESS_FILE"
else:
return "FAILED"
Best Practices
- Include error handling in file-based scripts (try/except with sys.stderr)
- Add success indicators (print statements) to confirm execution
- Preserve original logic when converting from inline to file
- Check return codes when executing scripts via shell
- Clean up temporary files after successful validation
- Log both stdout and stderr for debugging
Common Failure Scenarios
This pattern helps resolve:
- Heredoc string escaping issues
- Multi-line code formatting problems
- Import path resolution failures
- Environment variable access issues
- Complex indentation in inline code
FAQ
Why save the code to a file?
A saved file is easier to fix and run again than code passed inline, and it stays for review.
What does the validation step check?
It checks that the output is correct and complete, such as the expected rows or sheets being present.
Does the agent always start inline?
Yes, the skill says to try inline first and only switch to a file if that fails.
Details
Original description by the author
Four-step recovery workflow for code execution failures when inline Python fails
repo: HKUDS/AgentPilot
Popularity
- GitHub stars
- 7.8k
- Ranking position
- #12959
- License
- MIT
- Updated
- 11/1/2026
Comments
- …
More skills from this repository
agentpilot
7.8kHelps your agent improve a project step by step by preparing a task and running the AgentPilot loop that proposes, tests and scores changes.
openspace
7.8kHelps your agent set up OpenSpace, a tool that stores and fetches agent skills, and connect it to your AI app through MCP.
rsi-arena
7.8kHelps your agent set up and run standard AI benchmark tests, such as AIME and Terminal-Bench, to compare different improvement methods.
experiment-guide
7.8kHelps your agent plan small experiments, read their results and record findings while it investigates how to improve a program.
Similar skills
diffs
394kLets your agent produce a real, shareable diff of edits as a viewer link or image file, instead of a hand-written summary.
coding-agent
394kHelps your agent hand a larger coding job to Codex, Claude Code, or OpenCode as a background worker, then check on its progress.
gh-issues
394kHelps your agent find GitHub issues, pick the ones to work on, and open pull requests with fixes, including follow-up on review comments.