본문으로 건너뛰기
Skillpedia
일반 코딩7.8k · #12959

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가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/python-execution-fallback/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

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:

  1. Attempt inline execution first - Try running Python code directly
  2. Write script to file on failure - Persist the code to a .py file
  3. Execute the file - Run the saved script via shell
  4. 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

  1. Include error handling in file-based scripts (try/except with sys.stderr)
  2. Add success indicators (print statements) to confirm execution
  3. Preserve original logic when converting from inline to file
  4. Check return codes when executing scripts via shell
  5. Clean up temporary files after successful validation
  6. 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.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬