python-execution-fallback
하는 일
이 스킬은 Python 코드 실행이 실패할 때 AI 에이전트가 따를 명확한 단계 순서를 줍니다. Python 코드를 AI로 안정적으로 실행하려는 사람에게 맞습니다.
사용하는 경우
- ✓인라인 Python 코드가 구문 또는 실행 오류로 실패할 때.
- ✓heredoc 코드에서 파싱 문제가 생겨 더 안정적인 방법이 필요할 때.
- ✓인라인으로 실행하면 스프레드시트나 데이터 생성 작업이 실패하는 경우.
스킬 링크
https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/python-execution-fallback/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“인라인으로 실행하면 제 Python 코드가 계속 실패합니다. 스크립트로 저장해서 실행하고 결과를 확인해 주세요.”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
에이전트는 먼저 코드를 인라인으로 실행해 봅니다. 실패하면 전체 스크립트를 .py 파일로 저장하고, 셸로 그 파일을 실행하며, 출력이 완전하고 맞는지 확인합니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 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
자주 묻는 질문
코드를 파일로 저장하는 이유는 무엇인가요?
저장된 파일은 인라인 코드보다 고치고 다시 실행하기 쉬우며, 검토를 위해 남습니다.
검증 단계에서는 무엇을 확인하나요?
출력이 맞고 완전한지, 예를 들어 예상한 행이나 시트가 있는지 확인합니다.
에이전트는 항상 인라인으로 시작하나요?
네, 스킬은 먼저 인라인으로 시도하고, 그것이 실패할 때만 파일로 전환하라고 말합니다.
상세 정보
작성자의 원본 설명
Four-step recovery workflow for code execution failures when inline Python fails
repo: HKUDS/AgentPilot
인기도
- GitHub 스타
- 7.8k
- 순위
- #12959
- 라이선스
- MIT
- 업데이트
- 2026. 11. 1.
댓글
- …
이 저장소의 다른 스킬
agentpilot
7.8k작업을 준비하고 AgentPilot 루프를 실행해 변경을 제안, 테스트, 점수화하면서 프로젝트를 단계적으로 개선하도록 돕습니다.
openspace
7.8k에이전트 스킬을 저장하고 가져오는 도구인 OpenSpace를 설정하고, MCP를 통해 AI 앱에 연결하도록 돕습니다.
rsi-arena
7.8kAIME나 Terminal-Bench 같은 표준 AI 벤치마크 테스트를 설정하고 실행해 서로 다른 개선 방법을 비교하도록 돕습니다.
experiment-guide
7.8k프로그램을 개선하는 방법을 조사하면서 작은 실험을 계획하고, 결과를 읽고, 발견 사항을 기록하도록 돕습니다.