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

fallback-python-shell

하는 일

이 스킬은 평소 도구가 실패할 때 셸에서 Python 코드를 직접 실행해 파일을 읽고 데이터를 처리합니다. 평소 도구가 고장 났을 때 문서, 스프레드시트 또는 데이터를 처리해야 하는 사람에게 맞습니다.

사용하는 경우

  • ✓샌드박스가 작업 중 알 수 없는 오류를 낼 때.
  • ✓파일 읽기 도구가 지원되는 형식의 파일을 읽지 못하는 경우.
  • ✓텍스트, JSON, CSV 또는 Excel 파일을 읽고 처리해야 할 때.

스킬 링크

https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/fallback-python-shell/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/fallback-python-shell/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분.

작동 방식

AI는 셸 heredoc에서 짧은 Python 스크립트를 실행합니다. 스크립트는 파일을 열고 내용을 처리한 뒤 결과를 대화에 출력합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Shell-Based Python Fallback

When to Use

Use this fallback pattern when:

  • execute_code_sandbox returns 'unknown error'
  • read_file returns 'unknown error' for supported formats
  • You need to process documents, analyze data, or read files programmatically

Core Technique

Run Python code through run_shell using a heredoc. This bypasses sandbox execution issues while maintaining Python's full capabilities for file I/O and data processing.

Basic Pattern

python3 << 'EOF'
# Your Python code here
import json
import os

# Example: Read and process a file
with open('/path/to/file.txt', 'r') as f:
    content = f.read()
    print(content)
EOF

Key Syntax Points

  1. Use python3 << 'EOF' (quoted EOF prevents variable expansion in the heredoc)
  2. Indent Python code starting from column 0 (no extra indentation from shell)
  3. End with EOF on its own line with no leading/trailing whitespace
  4. Print results to stdout to capture them in the tool response

Common Use Cases

Reading Files (Fallback for read_file)

python3 << 'EOF'
import json

# Read text file
with open('document.txt', 'r') as f:
    content = f.read()
    print(content)

# Read JSON file
with open('data.json', 'r') as f:
    data = json.load(f)
    print(json.dumps(data, indent=2))
EOF

Processing Excel/CSV Files

python3 << 'EOF'
import pandas as pd

# Read Excel file
df = pd.read_excel('data.xlsx', sheet_name='Sheet1')
print(df.to_string())
print(f"Shape: {df.shape}")

# Read CSV
df = pd.read_csv('data.csv')
print(df.head(10))
EOF

Reading PDF Files

python3 << 'EOF'
import fitz  # PyMuPDF

doc = fitz.open('document.pdf')
for page_num in range(len(doc)):
    page = doc[page_num]
    text = page.get_text()
    print(f"=== Page {page_num + 1} ===")
    print(text)
doc.close()
EOF

Reading Word Documents

python3 << 'EOF'
from docx import Document

doc = Document('document.docx')
for para in doc.paragraphs:
    print(para.text)
EOF

Data Analysis

python3 << 'EOF'
import pandas as pd
import numpy as np

df = pd.read_csv('data.csv')

# Basic statistics
print(f"Shape: {df.shape}")
print(f"Columns: {list(df.columns)}")
print(df.describe())

# Filter and aggregate
result = df.groupby('category').agg({'value': 'sum'})
print(result)
EOF

Best Practices

  1. Error Handling: Wrap file operations in try/except blocks

    python3 << 'EOF'
    try:
        with open('file.txt', 'r') as f:
            content = f.read()
            print(content)
    except FileNotFoundError:
        print("ERROR: File not found")
    except Exception as e:
        print(f"ERROR: {e}")
    EOF
    
  2. Large Output: For large files, process in chunks or print summaries

    python3 << 'EOF'
    with open('large_file.csv', 'r') as f:
        for i, line in enumerate(f):
            if i < 10:
                print(line.strip())
            else:
                print("... truncated ...")
                break
    EOF
    
  3. Working Directory: Remember run_shell executes in the current working directory. Use absolute paths or ensure you're in the right directory.

  4. Multiple Steps: Chain related operations in a single heredoc rather than multiple calls

    python3 << 'EOF'
    # Do all related work in one call
    with open('input.json') as f:
        data = json.load(f)
    
    processed = [transform(x) for x in data]
    
    with open('output.json', 'w') as f:
        json.dump(processed, f)
    
    print("Processing complete")
    EOF
    

Troubleshooting

  • Module not found: Some packages may not be available. Stick to standard library or commonly pre-installed packages (pandas, numpy are often available).
  • Permission errors: Ensure files aren't in protected directories.
  • Character encoding: Specify encoding explicitly: open('file.txt', 'r', encoding='utf-8')
  • Very long code: Split into multiple heredocs or write to a temporary .py file first.
자주 묻는 질문

heredoc은 무엇인가요?

여러 줄의 코드를 한 번에 셸 명령에 보내는 방법입니다.

어떤 파일 형식이 언급되나요?

가이드는 일반 텍스트, JSON, pandas로 처리하는 CSV나 Excel 파일을 언급합니다.

결과를 왜 출력하나요?

출력된 내용이 대화로 돌아오므로 AI가 읽고 보고할 수 있기 때문입니다.

상세 정보

작성자의 원본 설명

Use run_shell with Python heredoc when execute_code_sandbox or read_file fail

repo: HKUDS/AgentPilot

인기도

GitHub 스타
7.8k
순위
#12883
라이선스
MIT
업데이트
2026. 11. 1.

이 스킬이 유용한가요?

0

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

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬