Files
sandbox.files works on the sandbox’s file system through the guest agent. Paths are absolute.
Basics
Section titled “Basics”from svm import Sandbox
with Sandbox.create(template="base") as sandbox: files = sandbox.files files.make_dir("/tmp/docs") files.write("/tmp/docs/hello.txt", "hello, sandbox\n") print(files.read_text("/tmp/docs/hello.txt"))
for entry in files.list("/tmp/docs"): print(entry.name, entry.type, entry.size)
print(files.exists("/tmp/docs/hello.txt")) # True info = files.get_info("/tmp/docs/hello.txt") print(info.path, info.size, info.permissions)
files.rename("/tmp/docs/hello.txt", "/tmp/docs/greeting.txt") files.remove("/tmp/docs")import { Sandbox } from "@svm/sandbox";
const sandbox = await Sandbox.create({ template: "base" });try { const files = sandbox.files; await files.makeDir("/home/user/project"); await files.write("/home/user/project/notes.txt", "hello, files\n"); console.log(await files.readText("/home/user/project/notes.txt"));
for (const entry of await files.list("/home/user/project")) { console.log(entry.type, entry.name, entry.size); }
console.log(await files.exists("/home/user/project/notes.txt")); // true const info = await files.getInfo("/home/user/project/notes.txt"); console.log(info.size, info.permissions, info.modifiedAt);
await files.rename("/home/user/project/notes.txt", "/home/user/project/readme.txt"); await files.remove("/home/user/project/readme.txt");} finally { await sandbox.kill();}files, err := sandbox.Files()if err != nil { return err}if _, err := files.MakeDir(ctx, "/tmp/docs"); err != nil { return err}if _, err := files.Write(ctx, "/tmp/docs/hello.txt", []byte("hello, sandbox"), 0o644); err != nil { return err}text, err := files.ReadText(ctx, "/tmp/docs/hello.txt")if err != nil { return err}fmt.Println(text)
entries, err := files.List(ctx, "/tmp/docs", 1)if err != nil { return err}for _, entry := range entries { fmt.Println(entry.Name, entry.Type, entry.Size)}exists, err := files.Exists(ctx, "/tmp/docs/hello.txt")if err != nil { return err}info, err := files.GetInfo(ctx, "/tmp/docs/hello.txt")if err != nil { return err}fmt.Println("exists:", exists, "size:", info.Size, "modified:", info.ModifiedAt)
if _, err := files.Rename(ctx, "/tmp/docs/hello.txt", "/tmp/docs/renamed.txt"); err != nil { return err}require "svm"
box = SVM::Sandbox.create(template: "base")begin files = box.files files.make_dir("/home/user/notes") files.write("/home/user/notes/todo.txt", "buy milk\n") puts files.read_text("/home/user/notes/todo.txt")
files.list("/home/user/notes").each { |entry| puts "#{entry['name']} #{entry['size']}" }
puts files.exists?("/home/user/notes/todo.txt") # true info = files.get_info("/home/user/notes/todo.txt") puts "#{info['path']} is #{info['size']} bytes"
files.rename("/home/user/notes/todo.txt", "/home/user/notes/done.txt") files.remove("/home/user/notes/done.txt") puts files.exists?("/home/user/notes/done.txt") # falseensure box.killendimport dev.svm.sandbox.Client;import dev.svm.sandbox.FileClient;import dev.svm.sandbox.Sandbox;import java.util.Map;
public class FilesBasicsExample { public static void main(String[] args) { Client client = Client.fromEnvironment(); try (Sandbox sandbox = Sandbox.create(client, "base")) { FileClient files = sandbox.files();
files.makeDir("/home/user/notes"); files.write("/home/user/notes/todo.txt", "buy milk\n"); System.out.print(files.readText("/home/user/notes/todo.txt"));
for (Map<String, Object> entry : files.list("/home/user/notes", 1)) { System.out.println(entry.get("name") + " " + entry.get("size")); }
System.out.println("exists: " + files.exists("/home/user/notes/todo.txt")); System.out.println("info: " + files.getInfo("/home/user/notes/todo.txt"));
files.rename("/home/user/notes/todo.txt", "/home/user/notes/done.txt"); files.remove("/home/user/notes/done.txt"); } }}Batches, binary data and signed URLs
Section titled “Batches, binary data and signed URLs”write_batch writes several files in one round trip. read returns bytes and accepts an offset and a limit for ranged reads.
For large files, upload_url and download_url give a short-lived signed URL that any HTTP client can use without your API key.
Treat the URL as a credential.
from svm import Sandbox
with Sandbox.create(template="base") as sandbox: sandbox.files.write_batch({ "/tmp/app/main.py": "print('hello')\n", "/tmp/app/README.md": "# app\n", })
sandbox.files.write("/tmp/app/blob.bin", bytes(range(256))) data = sandbox.files.read("/tmp/app/blob.bin") # bytes print(len(data), data[:4])
# Signed URLs let another machine fetch or send a file without the API key. download = sandbox.files.download_url("/tmp/app/main.py", expires_in_seconds=600) upload = sandbox.files.upload_url("/tmp/app/upload.txt") print("download:", download.url, "until", download.expires_at) print("upload:", upload.url)import { Sandbox } from "@svm/sandbox";
const sandbox = await Sandbox.create({ template: "base" });try { await sandbox.files.writeBatch({ "/home/user/app/main.py": "print('hi')\n", "/home/user/app/config.json": JSON.stringify({ debug: true }), });
const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x00, 0xff]); await sandbox.files.write("/home/user/app/blob.bin", bytes); const back: Uint8Array = await sandbox.files.read("/home/user/app/blob.bin"); console.log(back.length, back[0]);
const download = await sandbox.files.downloadUrl("/home/user/app/main.py", { expiresInSeconds: 300 }); const upload = await sandbox.files.uploadUrl("/home/user/app/upload.txt"); console.log(download.url, download.expiresAt); console.log(upload.url);} finally { await sandbox.kill();}files, err := sandbox.Files()if err != nil { return err}written, err := files.WriteBatch(ctx, map[string][]byte{ "/tmp/project/a.txt": []byte("alpha"), "/tmp/project/b.txt": []byte("beta"),}, 0o644)if err != nil { return err}fmt.Println("wrote", len(written), "files")
blob := []byte{0x89, 'P', 'N', 'G', 0x00, 0xff, 0x10}if _, err := files.Write(ctx, "/tmp/project/data.bin", blob, 0o644); err != nil { return err}got, err := files.Read(ctx, "/tmp/project/data.bin", 0, 0) // offset 0, limit 0: the whole fileif err != nil { return err}fmt.Println("same bytes:", bytes.Equal(got, blob))
download, err := files.DownloadURL(ctx, "/tmp/project/data.bin", svm.FileURLOptions{ExpiresInSeconds: 300})if err != nil { return err}upload, err := files.UploadURL(ctx, "/tmp/project/upload.bin", svm.FileURLOptions{ExpiresInSeconds: 300})if err != nil { return err}fmt.Println("GET", download.URL, "until", download.ExpiresAt)fmt.Println("PUT", upload.URL)require "svm"
box = SVM::Sandbox.create(template: "base")begin files = box.files files.write_batch( "/home/user/app/main.py" => "print('hi')\n", "/home/user/app/README.md" => "# app\n" )
png_header = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A].pack("C*") files.write("/home/user/app/logo.png", png_header) bytes = files.read("/home/user/app/logo.png") # a binary String puts "read #{bytes.bytesize} bytes"
# Signed URLs for a plain HTTP GET or PUT, no SDK needed. Treat them as secrets. download = files.download_url("/home/user/app/main.py", expires_in_seconds: 600) upload = files.upload_url("/home/user/app/data.csv") puts "GET #{download['url']} (until #{download['expires_at']})" puts "PUT #{upload['url']}"ensure box.killendimport dev.svm.sandbox.Client;import dev.svm.sandbox.FileClient;import dev.svm.sandbox.Sandbox;import java.nio.charset.StandardCharsets;import java.util.Arrays;import java.util.Map;
public class FilesBatchBinaryExample { public static void main(String[] args) { Client client = Client.fromEnvironment(); try (Sandbox sandbox = Sandbox.create(client, "base")) { FileClient files = sandbox.files();
files.writeBatch(Map.of( "/home/user/app/main.py", "print('hi')\n".getBytes(StandardCharsets.UTF_8), "/home/user/app/README.md", "# app\n".getBytes(StandardCharsets.UTF_8)));
byte[] blob = {0, 1, 2, (byte) 0xff}; files.write("/home/user/app/blob.bin", blob); byte[] back = files.read("/home/user/app/blob.bin"); System.out.println("same bytes: " + Arrays.equals(blob, back));
// Signed URLs for a plain HTTP transfer, valid for 300 s by default. Map<String, Object> download = files.downloadUrl("/home/user/app/blob.bin"); Map<String, Object> upload = files.uploadUrl("/home/user/app/upload.bin"); System.out.println("GET " + download.get("url") + "\nPUT " + upload.get("url")); } }}Watch a directory
Section titled “Watch a directory”watch_dir streams create, write, rename and remove events for a directory.
from svm import Sandbox
with Sandbox.create(template="base") as sandbox: sandbox.files.make_dir("/tmp/inbox")
# Another process writes into the directory while we watch it. sandbox.commands.run( "sleep 1; for i in 1 2 3; do echo $i > /tmp/inbox/file$i.txt; sleep 0.5; done", background=True, )
for event in sandbox.files.watch_dir("/tmp/inbox"): print(event.type, event.name) if event.name == "file3.txt": breakimport { Sandbox } from "@svm/sandbox";
const sandbox = await Sandbox.create({ template: "base" });try { await sandbox.files.makeDir("/home/user/inbox"); const watcher = await sandbox.files.watchDir("/home/user/inbox", (event) => { console.log(event.type, event.name); });
await sandbox.commands.run("for i in 1 2 3; do echo $i > /home/user/inbox/file-$i.txt; sleep 0.5; done"); await new Promise((resolve) => setTimeout(resolve, 1000)); // let the last events arrive watcher.close();} finally { await sandbox.kill();}watchCtx, cancel := context.WithTimeout(ctx, 15*time.Second)defer cancel()events, errs, stop, err := files.WatchDir(watchCtx, "/tmp/watched", false)if err != nil { return err}defer stop()
go commands.Run(ctx, "for i in 1 2 3; do echo $i > /tmp/watched/file$i.txt; sleep 1; done", svm.RunOptions{})
for { select { case event, ok := <-events: if !ok { return nil } fmt.Println(event.Type, event.Name) case err := <-errs: return err case <-watchCtx.Done(): return nil }}require "svm"
box = SVM::Sandbox.create(template: "base")begin box.files.make_dir("/home/user/inbox")
# Something else writes into the directory a moment later. box.commands.run("sleep 1; for n in 1 2 3; do echo $n > /home/user/inbox/file-$n.txt; done", background: true)
# Blocks, yielding each event; stops after 3 events (or when the block throws :stop). box.files.watch_dir("/home/user/inbox", count: 3) do |event| puts "#{event['type']} #{event['name']}" endensure box.killendimport dev.svm.sandbox.Client;import dev.svm.sandbox.RunOptions;import dev.svm.sandbox.Sandbox;
public class FilesWatchExample { public static void main(String[] args) { Client client = Client.fromEnvironment(); try (Sandbox sandbox = Sandbox.create(client, "base")) { sandbox.files().makeDir("/home/user/inbox");
// Another command writes into the directory in the background. RunOptions background = new RunOptions(); background.background = true; sandbox.commands().run( "for i in 1 2 3; do sleep 1; echo $i > /home/user/inbox/file$i.txt; done", background);
// Blocks until 6 events were delivered, or the callback returns false. sandbox.files().watchDir("/home/user/inbox", false, false, 6, event -> { System.out.println(event.get("type") + " " + event.get("name")); return true; }); } }}Errors
Section titled “Errors”Reading a path that does not exist raises the SDK’s file-not-found error:
| SDK | Error |
|---|---|
| Python | SandboxFileNotFoundError |
| TypeScript | FileNotFoundError |
| Go | ErrFileNotFound |
| Ruby | FileNotFoundError |
| Java | ProcessException.FileNotFound |
A full disk raises NotEnoughSpaceError. See Errors and retries.