Aller au contenu principal

Reference · Python SDK

Python SDK

Public surface of the grotte PyPI package. Two equivalent entrypoints — Sandbox (sync) and AsyncSandbox (async). Hand-curated from docstrings.

Install

bash
pip install grotte

Two entrypoints — pick the one that matches your code:

py
from grotte import Sandbox          # sync
from grotte import AsyncSandbox     # async (use with await)

Method names are identical between the two; the async version returns awaitables. Examples below show the sync API; for async, prefix every call with await and the surrounding context manager with async with.


Sandbox / AsyncSandbox

Lifecycle

MethodReturnsDescription
Sandbox.create(template=None, **opts)SandboxCreate from a template (default base).
Sandbox.connect(sandbox_id, **opts)SandboxReconnect to a running sandbox.
Sandbox.list(**opts)SandboxPaginatorIterate sandboxes (running by default).
sandbox.is_running(request_timeout=None)boolHealth probe.
sandbox.kill(...)NoneTerminate immediately.
sandbox.pause(...)boolPause + persist filesystem.
sandbox.resume(...)SandboxResume a paused sandbox. Alias for connect().
py
from grotte import Sandbox
 
with Sandbox.create("base") as sandbox:
    result = sandbox.commands.run('echo "Hello"')
    print(result.stdout)
# kill() called on context exit

Async equivalent:

py
from grotte import AsyncSandbox
 
async with await AsyncSandbox.create("base") as sandbox:
    result = await sandbox.commands.run('echo "Hello"')
    print(result.stdout)

Timeout / TTL

MethodReturnsDescription
set_timeout(timeout, ...)NoneSet total max lifetime (seconds, from now).
refresh_ttl(seconds, ...)NoneAdd seconds to current TTL (heartbeat-style).

Network

MethodReturnsDescription
set_network(internet_access=True, ...)NoneToggle outbound internet access.
py
sandbox.set_network(internet_access=False)  # cut egress for untrusted code

Snapshots

MethodReturnsDescription
create_snapshot(...)SnapshotInfoSnapshot the filesystem to a reusable template.

URLs

MethodReturnsDescription
get_host(port)strHost-only string.
get_url(port)strFull https://… URL — wraps get_host. Prefer this for previews.
upload_url(path=None, ...)strPre-signed upload URL.
download_url(path, ...)strPre-signed download URL.

sandbox.filesystem · alias sandbox.files

Both names point at the same Filesystem instance — filesystem is the canonical attribute, files exists for typing brevity in user code.

MethodReturnsDescription
read(path, format="text", ...)str | bytes | IteratorRead a file. formattext (default), bytes, stream.
write(path, data, ...)EntryInfoWrite a file (data accepts str or bytes).
write_files(files, ...)list[EntryInfo]Batch-write many files in one round-trip.
list(path, ...)list[EntryInfo]List directory entries.
make_dir(path, ...)boolmkdir -p.
rename(src, dst, ...)EntryInfoRename / move.
remove(path, ...)Nonerm -rf.
exists(path, ...)boolCheck if a path exists.
get_info(path, ...)EntryInfoStat-like metadata for a path.
py
sandbox.filesystem.write("/tmp/hello.txt", "world")
print(sandbox.filesystem.read("/tmp/hello.txt"))  # "world"

sandbox.commands

MethodReturnsDescription
run(command, ...)CommandResultRun a command, wait for exit, return (stdout, stderr, exit_code).
connect(pid, ...)CommandHandleAttach to an already-running command.
list(...)list[ProcessInfo]List currently-running processes.
kill(pid, ...)boolSIGKILL by pid.
send_stdin(pid, data, ...)NonePipe data into a running process's stdin.
py
result = sandbox.commands.run("python -c 'print(2+2)'")
print(result.stdout)  # "4\n"

For long-running processes, set background=True and stream output from the returned handle:

py
handle = sandbox.commands.run("npm run dev", background=True)
for chunk in handle.stdout:
    print(chunk, end="")

sandbox.pty · interactive PTY

For commands that need a real terminal (REPLs, full-screen TUI apps, interactive prompts):

py
pty = sandbox.pty.create(rows=24, cols=80)
pty.send_stdin(b"python\n")
output = pty.read()
pty.kill()

sandbox.git

Convenience wrappers around git operations inside the sandbox — clone, pull, status. Same shape as the underlying commands.run("git ...") calls, with typed returns.


Templates (build-time)

Two builder classes, parallel to the runtime split:

py
from grotte import Template, AsyncTemplate
 
template = (
    Template()
    .from_image("ubuntu:22.04")
    .run_cmd("apt-get update && apt-get install -y python3-pip")
    .run_cmd("pip install pandas")
    .set_workdir("/opt/work")
)

See Defining a template for the full builder API.


Common kwargs

Every method accepts:

KwargTypeDescription
request_timeoutfloat | NonePer-request timeout in seconds.

API key is read from the GROTTE_API_KEY env var by default; override per-call via api_key=....


See also