本文引導你通過 E2B SDK 建立第一個雲沙箱,並在其中執行一條命令。
前置條件
已擁有阿里雲帳號,並具備Function Compute相關操作許可權。
已在Function Compute控制台建立 API Key。
已確認目標地區支援雲沙箱,並且本機網路可訪問該地區的雲沙箱服務。
使用 Python 樣本時,已安裝 Python 3.10 或更高版本。
使用 TypeScript 樣本時,已安裝 Node.js 20.18.1 或更高版本。
SDK 版本要求、支援地區和 Endpoint 規則參見使用約束。
1. 配置環境變數
通過環境變數傳入 API Key、Endpoint 和網域名稱,不要將其寫入程式碼在代碼中。API Key 的建立和管理方式參見建立 API Key。
export E2B_API_KEY="<YOUR-API-KEY>"
export E2B_API_URL="https://api.<region>.e2b.fc.aliyuncs.com"
export E2B_DOMAIN="<region>.e2b.fc.aliyuncs.com"其中 <region> 為雲沙箱服務所在地區。
2. 安裝 E2B SDK
Python
先確認 Python 版本為 3.10 或更高版本,然後建立並啟用虛擬環境、安裝 E2B SDK:
python3 --versionpython3 -m venv .venv
source .venv/bin/activate
pip install e2b==2.31.0 e2b-code-interpreter==2.8.1TypeScript
先確認 Node.js 版本為 20.18.1 或更高版本,然後初始化專案、安裝 E2B SDK 及開發依賴:
node --versionnpm init -y
npm install e2b@^2.31.0 @e2b/code-interpreter@^2.6.1
npm install -D tsx typescript @types/node3. 建立並運行 Sandbox
選擇 Python 或 TypeScript 樣本運行即可。
Python
建立 quickstart.py:
import os
from e2b_code_interpreter import Sandbox
def require_env(name: str) -> str:
value = os.environ.get(name, "").strip()
if not value:
raise RuntimeError(f"缺少環境變數: {name}")
return value
sandbox = None
try:
sandbox = Sandbox.create(
template="code-interpreter-v1",
api_key=require_env("E2B_API_KEY"),
api_url=require_env("E2B_API_URL"),
domain=require_env("E2B_DOMAIN"),
)
result = sandbox.commands.run("python3 -c \"print('hello from sandbox')\"")
print(result.stdout.strip())
finally:
if sandbox is not None:
sandbox.kill()運行:
python3 quickstart.pyTypeScript
建立 quickstart.ts:
import { Sandbox } from "@e2b/code-interpreter";
async function main() {
const sandbox = await Sandbox.create("code-interpreter-v1", {
apiKey: process.env.E2B_API_KEY,
apiUrl: process.env.E2B_API_URL,
domain: process.env.E2B_DOMAIN,
timeoutMs: 300_000,
});
try {
const result = await sandbox.commands.run("python3 -c \"print('hello from sandbox')\"");
console.log(result.stdout.trim());
} finally {
await sandbox.kill();
}
}
main();運行:
npx tsx quickstart.ts如果能看到 hello from sandbox,說明 SDK、API Key、Endpoint、網域名稱和內建模板都已可用。