본문으로 건너뛰기
cccskills
무료GitHub에 공개

python-execution-fallback

Recover from failed inline Python execution by saving the code as a script, running it through the shell, and checking the output. The four-step workflow helps diagnose errors in multiline code and spreadsheet generation tasks.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

원문원문 설명 보기

Four-step recovery workflow for code execution failures when inline Python fails

연동 도구Excel
설치 방법 보기

이럴 때 유용합니다

  • Recovering from failed inline Python execution
  • Diagnosing heredoc parsing errors
  • Debugging complex multiline scripts
  • Checking spreadsheet generation results

포함된 파일(2)

  • SKILL.md4.7 KB
  • .skill_id39 B

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

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

Related Patterns

  • Combine with retry-with-modification for iterative debugging
  • Use alongside output-validation-check for result verification
  • Pair with error-log-analysis for root cause identification

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Prepare audio stems, the separate parts of a track, for mixing by matching their durations with silence, loops, or crossfades. Verify each generated and processed file before moving to the next production step.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Match audio parts with different durations
  • Extend drums and melodic parts using suitable methods
  • Check audio specifications before mixing
HKUDS/OpenSpace7.8천2026년 8월 13일 업데이트

Produce audio in separate stems, meaning individual instrument tracks, and verify each output as you go. Align track lengths with silence, loops, or crossfades, then apply effects, mix a master, and package the files.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Align instrument tracks to a reference audio file
  • Choose how to extend tracks that are too short
  • Verify audio properties after generation and effects
HKUDS/OpenSpace7.8천2026년 8월 13일 업데이트

Build serverless endpoints that relay external API requests for a dashboard while keeping API keys on the server. Includes Vercel examples for input checks, caching, cross-origin access, and consistent JSON responses.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Connect a dashboard to external APIs without exposing API keys
  • Create endpoints for stock quotes and news
  • Standardize API responses and error handling
HKUDS/OpenSpace7.8천2026년 8월 13일 업데이트

Produce a master track and separate audio parts through a structured Python workflow. Apply filters and reverb, export WAV files with consistent settings, package them in a ZIP archive, and check that the deliverables meet the requested specifications.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Export a master track with separate audio parts
  • Apply filters and reverb to audio
  • Check duration and format across deliverables
HKUDS/OpenSpace7.8천2026년 8월 13일 업데이트

Keep document creation moving when web searches and page retrieval repeatedly fail. The skill preserves the original task, uses the model’s existing knowledge, and clearly identifies information that could not be checked against external sources.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Continue drafting after repeated web retrieval failures
  • Preserve task requirements during network errors
  • Mark information that could not be externally verified
HKUDS/OpenSpace7.8천2026년 8월 13일 업데이트

When Python execution repeatedly fails in execute_code_sandbox, use a file-based alternative: save the script, run it through the shell, and capture results or errors. The guidance covers paths, imports, timeouts, structured output, and optional cleanup.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Retry Python work through the shell after repeated sandbox failures
  • Run longer tasks with an adjusted timeout
  • Execute Python work that needs multiple files or system utilities
HKUDS/OpenSpace7.8천2026년 8월 13일 업데이트

HKUDS의 스킬 모두 보기

이 스킬의 문제 신고