你需要把项目的 API 密钥放在 GLAC_API_KEY 中,并安装 glac 或 Python SDK:入门里有做法。
用命令行
在专门为它创建、用完即删的沙箱中运行一条命令。退出码就是命令的退出码:
glac run --image python:3.12 -- python3 -c 'print(6*7)'一个一直保留到你删除它的沙箱:
glac sandboxes create --name web --image python:3.12 # prints its id
glac sandboxes exec web -- python3 --version # exits with the command's code
echo '<h1>hello</h1>' > index.html
glac sandboxes cp index.html web:/srv/ # copy files in, and out
glac sandboxes exec web --detach -- python3 -m http.server 3000 --directory /srv
glac sandboxes url web 3000 # a link to port 3000: whoever has it can open it一个终端。按 Enter,再按 ~.,就会离开并让它继续运行;用 glac sandboxes shell web --join <exec id> 回到这个终端:
glac sandboxes shell web休眠、创建快照、分叉和回退:
glac sandboxes sleep web # sleeps now; the next command wakes it
glac sandboxes snapshots create web --name before-upgrade
copy=$(glac sandboxes fork web) # a copy that goes on from this moment
glac sandboxes exec "$copy" -- ls /srv
glac sandboxes restore web before-upgrade # back to the snapshot, in place
glac sandboxes rm "$copy" web # their snapshots stay
glac sandboxes snapshots rm before-upgrade没有唤醒命令:任何需要沙箱的东西都会唤醒它。glac sbx 是 glac sandboxes 的简写。每个命令都接受 --json,这时它打印 API 返回的内容;glac help sandboxes 列出这些命令,命令行页面有全部命令。
用 Python SDK
from glac import Glac
glac = Glac() # GLAC_API_KEY and GLAC_API_URL
print(glac.sandboxes.run("echo hello").stdout) # one command: made, run, deleted
sbx = glac.sandboxes.create(image="python:3.12", name="web")
res = sbx.run("python3 -c 'print(6*7)'")
print(res.exit_code, res.stdout) # 0 42
sbx.files.write("/srv/index.html", "<h1>hello</h1>")
print(sbx.files.read_text("/srv/index.html"))
server = sbx.exec("python3 -m http.server 3000 --directory /srv") # starts it, does not wait
print(sbx.url(3000)) # a link to port 3000
sbx.sleep() # the next call wakes it
snap = sbx.snapshot(name="before-upgrade")
copy = sbx.fork(1)[0] # goes on from this moment
sbx.restore(snap) # back to the snapshot, in place
copy.delete()
sbx.delete()
snap.delete() # a snapshot outlives its sandboxwith glac.sandboxes.create() as sbx: 会在代码块结束时删除沙箱。以非零退出码退出的命令是一个结果,不是异常:读取 res.exit_code 即可。API 的错误会抛出 GlacError,带有 status、code、message 和 request_id。其余内容见 Python SDK 页面。
在控制台中
打开[控制台](https://console.glac.ai/console/),选择项目,在 Compute 下选择 Sandboxes。New sandbox 从镜像或模板创建一个沙箱,并可以设置规格。沙箱的页面显示它的状态和它在运行的原因、它的命令及其输出、一个运行命令的输入框,以及 Terminal、Sleep、Restart 和 Delete 按钮。关闭终端面板后终端仍在:Attach 回到它。