用途
本技能提供一种代码执行回退模式(Code Execution Fallback Pattern),用于在 execute_code_sandbox 反复失败时,改用更可靠的方式执行代码。
何时使用
当遇到 execute_code_sandbox 反复失败时应用此模式,具体包括:
- 连续 2 次及以上失败,且错误不透明或未知
- 超时错误在多次重试后仍然存在
- 环境相关错误,无法通过修改代码解决
回退工作流
第 1 步:检测重复失败
跟踪执行失败情况。在 execute_code_sandbox 连续失败 2 次后,切换到回退方案。
第 2 步:将脚本写入文件
使用 write_file 保存 Python 脚本:
write_file(
path="/workspace/script_name.py",
content="# Your Python code here\nimport sys\n..."
)
第 3 步:通过 Shell 执行
使用 run_shell 运行脚本:
run_shell(
command="python /workspace/script_name.py",
timeout=300
)
第 4 步:捕获输出
解析 run_shell 输出中的 stdout/stderr,以验证成功或诊断问题。
完整示例
# Instead of this (which may fail):
result = execute_code_sandbox(code="import pandas as pd\n...")
# Use this fallback pattern:
script_content = """
import pandas as pd
import sys
try:
# Your logic here
df = pd.DataFrame({'col': [1, 2, 3]})
print(df.to_csv())
sys.exit(0)
except Exception as e:
print(f"ERROR: {e}", file=sys.stderr)
sys.exit(1)
"""
# Write the script
write_file(path="/workspace/my_script.py", content=script_content)
# Execute via shell
result = run_shell(command="python /workspace/my_script.py", timeout=300)
最佳实践
- 在脚本中添加错误处理——使用 try/except 配合 sys.exit() 返回码
- 设置合适的超时——run_shell 默认 30 秒,重操作需增加
- 如有需要,执行后清理临时文件
- 记录回退触发原因——说明为何切换方案
- 确认 Python 可用性——大多数沙箱默认带有 Python 3.x
为什么有效
- write_file 在文件 I/O 操作上更可靠
- run_shell 让你直接控制执行环境
- Shell 执行绕过沙箱序列化问题
- 通过 stdout/stderr 流获得更好的错误可见性
何时不应使用此模式
- 首次执行失败(应先重试沙箱)
- 简单的单行代码(沙箱更快)
- 沙箱错误明显是代码 bug(应改为修复代码)
- 需要沙箱隔离的安全敏感操作