Workaround for executing Python code with external packages when sandbox fails
复制下面这句话,粘贴给 Claude Code、Codex、Cursor 等 AI 编程工具,它会读取安装说明并在你确认后完成安装。
请阅读 https://ai.atlankj.com/install/asset/gh-python-shell-workaround-801fca9ed92a ,按照其中的说明把「python-shell-workaround」安装到你(当前 AI 工具)中。执行前先告诉我将运行的命令和写入的位置,等我确认。
查看 AI 将读取的安装说明正在读取 GitHub 原文…
内容来自 GitHub 原始文件,由原作者维护。在 GitHub 查看
Use this pattern when execute_code_sandbox fails with Python code that requires external packages (like openpyxl, python-docx, pandas, etc.) that may not be available in the sandbox environment.
Instead of relying solely on execute_code_sandbox, use run_shell with inline Python commands as a fallback:
python3 -c "your python code here"
Watch for errors like:
Transform your Python script into a one-liner or use a heredoc for longer scripts:
For simple code:
python3 -c "import openpyxl; wb = openpyxl.Workbook(); wb.save('file.xlsx')"
For complex code (using heredoc):
python3 << 'EOF'
import openpyxl
from openpyxl.utils import get_column_letter
wb = openpyxl.Workbook()
ws = wb.active
ws['A1'] = 'Header'
wb.save('output.xlsx')
print('File created successfully')
EOF
Use run_shell to execute the command:
tool: run_shell
command: python3 -c "import openpyxl; print('Package available')"
Check the stdout/stderr from run_shell to confirm success, then proceed with subsequent steps.
pip install package before your Python command if packages are missing&& to ensure prerequisites succeed before running Python codepython3 << 'EOF'
import openpyxl
from openpyxl.worksheet.datavalidation import DataValidation
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Data"
# Add headers
headers = ['Name', 'Email', 'Status']
for col, header in enumerate(headers, 1):
ws.cell(row=1, column=col, value=header)
wb.save('output.xlsx')
EOF
python3 -c "
from docx import Document
doc = Document()
doc.add_heading('Report', 0)
doc.save('report.docx')
print('Document created')
"
pip install package_name && python3 -c "...".py file first, then execute with python3 script.py