Home Features Architecture Docs SDKs Get Started
TypeScript Python Go

Python

Blocking and async interfaces for Isolon with context managers, automatic cleanup, and bulk file transfers.

Add to your project

bash
pip install isolon

# or from source within the isolon repo
cd sdk/python
pip install -e .

Dependencies

requirements
httpx>=0.24
websockets>=11.0

Environment variables

VariableDescriptionDefault
ISOLON_API_URLIsolon server URLhttp://localhost:8080
ISOLON_API_KEYAPI key for authentication(none)

Your first sandbox

sandbox.py
from isolon import Sandbox

# Create a sandbox
sandbox = Sandbox.create(
    image="python:3.12-alpine",
    cpus=2,
    memory_mb=1024,
    envs={"OPENAI_API_KEY": os.environ["OPENAI_API_KEY"]},
    on_start=["pip install openai langchain"]
)

# Run commands
result = sandbox.commands.run("python --version")
print(result.stdout)  # Python 3.12.3

# Write and read files
sandbox.files.write("/app/main.py", "print('Hello')")
content = sandbox.files.read("/app/main.py")

# Commit for instant reuse
img = sandbox.commit("my-image")

# Cleanup
sandbox.close()

Python SDK

Static methods

MethodReturnsDescription
Sandbox.create(**kwargs)SandboxCreate a new sandbox. Waits for agent healthy before returning.
Sandbox.connect(id, **kwargs)SandboxConnect to an existing sandbox by ID.
Sandbox.list(**kwargs)list[Sandbox]List sandboxes. Optional label filtering via labels= dict.
Sandbox.list_profiles()list[Profile]List available pre-defined profiles from the server.
Sandbox.get_system_stats()SystemStatsGet server-level CPU/memory stats.

Instance properties & methods

MemberType / ReturnsDescription
idstrWorkspace ID
commandsCommandManagerExecute commands in the sandbox
filesFileManagerRead, write, list, watch files
gitGitManagerClone, commit, push, pull, branch operations
terminalTerminalManagerWebSocket PTY sessions
processProcessManagerList, kill, attach to processes
portsPortManagerList ports, wait for services, preview URLs
close()NoneDestroy the sandbox
pause()NonePause the VM (freeze state in memory)
resume()NoneResume a paused VM
is_running()boolCheck if the sandbox is healthy
get_info()SandboxInfoGet metadata: id, template_id, status, started_at
set_timeout(ms)NoneUpdate the auto-destroy timeout
run_code(code, language, context)ExecResultRun code in a persistent REPL context (python, js, bash)
commit(ref)dictSave filesystem as a reusable image. Returns {id, ref, status}.
fork()SandboxCreate a copy of this sandbox
snapshot()dictCapture full VM state. Returns {snapshot_path, mem_file_path}.
get_stats()dictCurrent CPU, memory, disk, network usage
stream_stats(cb)callableSubscribe to real-time stats via SSE. Returns unsubscribe function.
get_metrics()list[dict]Legacy E2B-compatible metrics format
update_memory(mb)NoneAdjust VM memory via balloon device
apply_sandbox_file(yaml_str)NoneApply a declarative Sandboxfile configuration
get_preview_url(port)strGet a shareable URL for a sandbox port
set_internet(enabled)NoneToggle outbound internet access
exec_in_terminal(cmd)NoneExecute a command through the active PTY
on_event(cb)callableSubscribe to lifecycle events. Returns unsubscribe function.
stream_logs(cb)callableSubscribe to serial console logs. Returns unsubscribe function.

CommandManager

MethodDescription
run(cmd, envs, background, on_stdout, on_stderr)Execute a command. Returns ExecResult with stdout, stderr, exit_code, pid.

FileManager

MethodDescription
read(path)Read a text file
read_bytes(path)Read a file as bytes
write(path, content)Write text or bytes
list(path)List directory contents with FileInfo entries
make_dir(path)Create a directory
exists(path)Check if a path exists
remove(path)Delete a file or directory
rename(old_path, new_path)Rename/move a file
watch(path, cb)Watch a directory for changes. Returns unsubscribe function.
watch_multiplex(paths, cb)Watch multiple directories over a single WebSocket
read_stream(path)Read a file as a stream (async)
write_stream(path, stream)Write from a stream (async)
upload_archive(data, remote_path)Upload a tar archive and extract it
download_archive(remote_path)Download a directory as a tar archive
upload_dir(files, remote_path)Upload multiple files from a dict
download_dir(remote_path)Download a directory as a dict of bytes

GitManager

MethodDescription
clone(url, **opts)Clone a repository. Options: path, branch, depth, username, password.
status(path)Get git status output
add(path, files)Stage files (all if files omitted)
commit(path, message, **opts)Commit changes. Options: author_name, author_email, allow_empty, files.
push(path, **opts)Push to remote. Options: remote, branch, username, password, set_upstream.
pull(path, **opts)Pull from remote. Options: remote, branch, username, password.
remote_add(path, name, url, **opts)Add a remote. Options: fetch, overwrite.
branches(path)List branches
create_branch(path, name)Create a new branch
checkout_branch(path, name, **opts)Checkout a branch. Options: force.
delete_branch(path, name)Delete a branch
get_config(key, **opts)Get a git config value. Options: scope, path.
set_config(key, value, **opts)Set a git config value. Options: scope, path.

TerminalManager & TerminalHandle

MethodDescription
terminal.connect()Open a WebSocket PTY session. Returns TerminalHandle.
terminal.resize(cols, rows)Resize the active PTY
terminal.exec_in_terminal(cmd)Execute a command through the active PTY
terminal.get_session_id()Get the current session ID
handle.write(data)Write data to terminal stdin
handle.on_data(cb)Register callback for terminal output
handle.resize(cols, rows)Resize the PTY
handle.wait(timeout)Wait for session to end
handle.close()Close the terminal session

ProcessManager

MethodDescription
process.list()List running processes with pid, ppid, cpu, mem, cmd
process.kill(pid, signal)Kill a process. Signal defaults to SIGKILL.
process.attach(pid, cb)Attach to a background process output stream. Returns unsubscribe.

PortManager

MethodDescription
ports.list()List open ports with protocol, state, and address
ports.wait_for_port(port, timeout_ms)Wait for a port to be listening
ports.get_preview_url(port)Get a shareable preview URL for a port

ImageManager

MethodDescription
ImageManager(url)Create an ImageManager instance for a server URL
img_mgr.convert(image_ref)Convert a Docker/OCI image to MicroVM rootfs
img_mgr.build(context, tag, dockerfile)Build from a tarball context
img_mgr.list()List images
img_mgr.get(image_id)Get image status
img_mgr.warm(image_id)Pre-create VM snapshot for faster boot
img_mgr.delete(image_id)Delete an image
img_mgr.list_templates()List cached templates
img_mgr.upload_template(buffer, name)Upload a template tarball
img_mgr.delete_template(name)Delete a template

Common patterns

Streaming command output

streaming.py
result = sandbox.commands.run(
    "for i in 1 2 3 4 5; do echo $i; sleep 1; done",
    on_stdout=lambda data: print(f"OUT: {data}", end=""),
    on_stderr=lambda data: print(f"ERR: {data}", end="")
)
print(f"Exit code: {result.exit_code}")

Background process with attach

background.py
result = sandbox.commands.run("python server.py", background=True)
print(f"Started process with PID: {result.pid}")

# Attach to stream its output
stop = sandbox.process.attach(
    result.pid,
    lambda data: print(f"OUTPUT: {data}")
)

# Later, stop streaming and kill
stop()
sandbox.process.kill(result.pid)

File watching

watch.py
stop = sandbox.files.watch(
    "/app/src",
    lambda event_type, file_name: print(f"{event_type}: {file_name}")
)

# ... do some work ...

stop()

Git workflow

git.py
sandbox.git.clone(
    "https://github.com/user/repo.git",
    path="/workspace/repo",
    branch="main",
    depth=1
)

sandbox.git.add("/workspace/repo")
sandbox.git.commit(
    "/workspace/repo",
    "Update",
    author_name="Dev",
    author_email="dev@example.com"
)
sandbox.git.push(
    "/workspace/repo",
    remote="origin",
    branch="main",
    username="user",
    password="token"
)

Bulk file transfer with tar

transfer.py
import tarfile, io

# Upload tar archive
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w") as tar:
    info = tarfile.TarInfo(name="data.txt")
    data = b"Hello World"
    info.size = len(data)
    tar.addfile(info, io.BytesIO(data))

sandbox.files.upload_archive(buf.getvalue(), "/app")

# Download tar archive
tar_data = sandbox.files.download_archive("/app/data")

Typed exceptions

errors.py
from isolon import (
    Sandbox,
    IsolonError,
    SandboxNotFoundError,
    QuotaExceededError,
    AuthenticationError
)

try:
    sandbox = Sandbox.create(image="python:3.12-alpine")
except AuthenticationError as e:
    print(f"Auth failed: {e}")
except QuotaExceededError as e:
    print(f"Rate limited: {e}")
except SandboxNotFoundError as e:
    print(f"Not found: {e}")
except IsolonError as e:
    print(f"Error: {e} (status: {e.status_code})")

# Or handle httpx errors directly
import httpx
from isolon.errors import map_api_error

try:
    sandbox = Sandbox.create(image="python:3.12-alpine")
except httpx.HTTPStatusError as e:
    raise map_api_error(e) from e