Python SDK
Classes, methods, options and defaults of the fdtn Python package. Times are in seconds.
1Install
Needs Python 3.11 or newer. The CLI install puts the SDK in ~/.fdtn; run your code with ~/.fdtn/bin/python.
$ curl -fsSL https://compute.fdtn.dev/install | sh -s -- --python $ fdtn auth $ ~/.fdtn/bin/python hello.py
In your own environment (also Windows):
$ pip install https://compute.fdtn.dev/install/fdtn-0.1.5-py3-none-any.whlThe SDK reads the key from api_key=, then FDTN_API_KEY, then ~/.fdtn/key. See API keys.
2Create a sandbox
from fdtn import Sandbox sbx = Sandbox.create( "base", timeout=600, # lifetime in seconds metadata={"run": "eval-1"}, envs={"MODE": "test"}, request_timeout=1800, # wait up to 30 minutes in the queue ) print(sbx.sandbox_id)
| Option | Default | What it does |
|---|---|---|
template | "base" | base, small, claude or your own. Sets the size. |
timeout | 300 (5 minutes) | Lifetime in seconds. Maximum 86400 (24 hours). |
metadata | {} | String pairs to find and group sandboxes. |
envs | {} | Environment variables for every command. After a resume, pass them per command (envs on commands.run). |
allow_internet_access | True | False blocks all outbound traffic. |
network | private ports | Dict: allow_public_traffic (default False), allow_out and deny_out (lists of addresses or ranges). |
lifecycle | kill on timeout | {"on_timeout": "pause"} pauses when the lifetime ends. |
request_timeout | 60 seconds | How long the SDK waits for an answer. 0: no limit. |
api_key, domain | see API keys | Key and service domain for this call. |
Metadata: up to 64 pairs, keys 1 to 128 bytes, values up to 1024 bytes. fdtn_ keys are reserved, except fdtn_own_fleet_only (Create options).
When machines are busy, a create waits in the queue for up to 30 minutes. For batch work, set request_timeout=1800.
3Run commands
sbx.commands.run waits and returns stdout, stderr and exit_code. A non-zero exit raises CommandExitException.
result = sbx.commands.run("python3 -c 'print(1 + 1)'") print(result.stdout) # "2\n" # Stream output; no time limit sbx.commands.run("pip install requests", on_stdout=print, on_stderr=print, timeout=0) # Background: returns a handle at once server = sbx.commands.run("python3 -m http.server 8000", background=True, timeout=0) server.kill()
| Option | Default | What it does |
|---|---|---|
background | False | True returns a handle at once. |
cwd | user's home folder | Folder to run in. |
user | template's user | User, such as "root". |
envs | {} | Variables for this command. Override the create envs. |
on_stdout, on_stderr | none | Functions that get output as it comes. |
stdin | False | True keeps standard input open for send_stdin. |
timeout | 60 seconds | Longest run time. 0: no limit. |
request_timeout | none | Not used here. timeout limits the start and the run. |
A background handle has pid, wait(), kill(), send_stdin(data), close_stdin() and disconnect(). By PID: sbx.commands.list(), connect(pid), send_stdin(pid, data), close_stdin(pid) and kill(pid).
4Read and write files
Every method also takes user= and request_timeout=. To copy folders, use fdtn cp -r (Files).
sbx.files.write("/app/input.json", '{"n": 3}') data = sbx.files.read("/app/model.bin", format="bytes") for entry in sbx.files.list("/app"): print(entry.name, entry.type, entry.size)
| Method | Returns | What it does |
|---|---|---|
read(path, format="text") | str, bytes or a stream | format: "text", "bytes" or "stream". |
write(path, data) | file info | Writes text, bytes or an open file. Makes missing folders. |
list(path, depth=1) | list of entries | Entries with name, type, path, size, modified_time and more. |
exists(path), get_info(path) | bool, entry | Checks one path. |
make_dir(path), rename(old_path, new_path), remove(path) | bool, entry, None | Makes, moves or removes. remove also removes folder contents. |
5Pause, resume and stop
Pause keeps memory and files and stops the charge. Sandbox.connect resumes from the same point (paused limits).
sandbox_id = sbx.sandbox_id sbx.pause() # Later, from any program with the same key: sbx = Sandbox.connect(sandbox_id) # resumes it sbx.kill()
| Method | What it does |
|---|---|
Sandbox.connect(sandbox_id, timeout=None) | Object for a sandbox; a paused one resumes. timeout sets a new lifetime; a running sandbox keeps a later end time. |
sbx.pause() | False if already paused. |
sbx.kill() | Ends the sandbox and deletes its files. |
sbx.set_timeout(seconds) | Time left, from now. Maximum 86400. |
sbx.get_info() | sandbox_id, template_id, metadata, started_at, end_at, state, cpu_count, memory_mb and more. |
sbx.is_running() | Tells if the sandbox answers. |
sbx.get_metrics(start=None, end=None) | Samples of CPU, memory and disk use. The first seconds have no samples. |
sbx.get_host(port) | Host name for a port (Ports). |
sbx.create_snapshot(name=None) | Saves the sandbox as a template. Give name, then start from it with Sandbox.create(name). Delete it with fdtn api /templates/<name> -X DELETE. |
Sandbox.list(query=None, limit=None, order=None) | Pager with has_next and next_items(). Usually one page, newest first. Sort on your side for another order. |
from fdtn import Sandbox, SandboxQuery, SandboxState pager = Sandbox.list(query=SandboxQuery(metadata={"run": "eval-1"}, state=[SandboxState.RUNNING, SandboxState.PAUSED])) while pager.has_next: for info in pager.next_items(): print(info.sandbox_id, info.state)
Timeouts
| Setting (seconds) | Where | Default | Limit |
|---|---|---|---|
| Sandbox lifetime | Sandbox.create(timeout=), set_timeout() | 300 | 86400 |
| Command run time | commands.run(timeout=) | 60 | 0 means no limit |
| Wait for an answer | request_timeout= on any call | 60 | 0 means no limit |
Errors
Import from fdtn or fdtn.exceptions. Status codes: HTTP API errors.
| Class | When |
|---|---|
AuthenticationException | No key, a wrong key, or an unsafe key file. |
CommandExitException | Non-zero exit. Has exit_code, stdout, stderr. |
TimeoutException | A timeout passed, or the lifetime ended. |
SandboxNotFoundException | Unknown or ended sandbox. |
NotFoundException, FileNotFoundException | A file, folder or template is missing. |
InvalidArgumentException | A wrong argument. |
NotEnoughSpaceException | The sandbox disk is full. |
RateLimitException | Too many requests or queued creates. Wait, then retry. |
ServiceBusyException | Retry in a moment. |
SandboxException | Base class of most errors, also 400 and 403. AuthenticationException and ServiceBusyException are separate: catch them too. |
from fdtn import CommandExitException try: sbx.commands.run("exit 3") except CommandExitException as e: print(e.exit_code, e.stderr) # 3
Async API
AsyncSandbox has the same methods as Sandbox. Await every call.
import asyncio from fdtn import AsyncSandbox async def one(i): sbx = await AsyncSandbox.create("base", metadata={"run": "demo"}, request_timeout=1800) try: r = await sbx.commands.run(f"echo {i}") return r.stdout.strip() finally: await sbx.kill() async def main(): print(await asyncio.gather(*(one(i) for i in range(10)))) asyncio.run(main())