Use run_shell with embedded Python heredoc as reliable fallback when code execution tools fail
复制下面这句话,粘贴给 Claude Code、Codex、Cursor 等 AI 编程工具,它会读取安装说明并在你确认后完成安装。
请阅读 https://ai.atlankj.com/install/asset/gh-shell-python-fallback-48b3c909dd86 ,按照其中的说明把「shell-python-fallback」安装到你(当前 AI 工具)中。执行前先告诉我将运行的命令和写入的位置,等我确认。
查看 AI 将读取的安装说明正在读取 GitHub 原文…
内容来自 GitHub 原始文件,由原作者维护。在 GitHub 查看
Use this pattern when execute_code_sandbox or shell_agent tools consistently fail with "unknown error" for tasks such as:
Instead of using code execution tools, embed your Python script directly in a run_shell command using a heredoc:
python3 << 'EOF'
# Your Python code here
import sys
print("Hello from embedded Python")
EOF
Identify the failure: When execute_code_sandbox or shell_agent returns "unknown error" repeatedly (2+ attempts), switch to this fallback.
Write your Python script: Prepare the complete Python code you need to execute.
Embed in run_shell: Use run_shell with a heredoc syntax:
Command: python3 << 'EOF'
import json
# Your complete script here
data = {"key": "value"}
print(json.dumps(data))
EOF
Handle multi-line scripts: For longer scripts, ensure proper indentation is preserved. The heredoc preserves whitespace exactly.
Check output: Parse the stdout from run_shell to verify success or capture errors.
python3 << 'EOF'
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
c = canvas.Canvas("output.pdf", pagesize=letter)
c.drawString(100, 750, "Hello World")
c.save()
print("PDF created successfully")
EOF
python3 << 'EOF'
import csv
import json
data = []
with open('input.csv', 'r') as f:
reader = csv.DictReader(f)
for row in reader:
data.append(row)
with open('output.json', 'w') as f:
json.dump(data, f, indent=2)
print(f"Processed {len(data)} records")
EOF
<< 'EOF' not << EOF) to prevent shell variable expansion in your Python code| Issue | Solution |
|---|---|
| Script doesn't run | Ensure python3 is available in the shell environment |
| Indentation errors | Check that heredoc preserves spaces (use spaces, not tabs) |
| Module not found | Use python3 -m pip install <module> before running script |
| File not found | Use absolute paths or pwd to verify working directory |
The run_shell tool executes commands directly in the system shell, bypassing the sandbox restrictions or internal errors that affect execute_code_sandbox and shell_agent. The heredoc approach allows multi-line Python scripts while keeping everything in a single shell command.