建立沙箱是使用雲沙箱的第一步。沙箱建立完成後,可以繼續執行命令、讀寫檔案、運行代碼或啟動臨時 HTTP 服務。
建立預設沙箱
import { Sandbox } from "e2b";
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,
});
try {
const result = await sandbox.commands.run("echo hello");
console.log(result.stdout.trim());
} finally {
await sandbox.kill();
}
Python 樣本:
import os
from e2b import Sandbox
sandbox = Sandbox.create(
template="code-interpreter-v1",
api_key=os.environ["E2B_API_KEY"],
api_url=os.environ["E2B_API_URL"],
domain=os.environ["E2B_DOMAIN"],
)
try:
result = sandbox.commands.run("echo hello")
print(result.stdout.strip())
finally:
sandbox.kill()
指定模板
當需要預裝依賴或固定運行環境時,可以通過模板建立沙箱:
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: 10 * 60 * 1000,
});
Python SDK 中,模板名稱或模板 ID 通過 template 參數傳入:
sandbox = Sandbox.create(
template="code-interpreter-v1",
api_key=os.environ["E2B_API_KEY"],
api_url=os.environ["E2B_API_URL"],
domain=os.environ["E2B_DOMAIN"],
timeout=10 * 60,
)
TypeScript SDK 中,模板名稱或模板 ID 通過 Sandbox.create(template, options) 的第一個參數傳入。options 常用參數包括:
-
timeoutMs:沙箱逾時時間,單位為毫秒。 -
envs:寫入沙箱運行環境的環境變數。 -
metadata:寫入沙箱控制面的自訂中繼資料。
使用建議
建立沙箱後,業務代碼應在 try/finally 中主動調用 sandbox.kill()。對於需要保留現場的任務,可以使用暫停與恢複,但不要用暫停替代資源釋放。