Skip to content

Reading and writing files

A sandbox’s files can be read and written from your code directly, without a command such as cat or cp in it. A path is the path in the guest without its leading /: etc/hostname is /etc/hostname.

Put a file in, and get one out

This writes an input file into the sandbox, runs a command on it, and reads what the command wrote:

await sandbox.create_dir_all("work")
await sandbox.write_file("work/input.txt", "one two three\n")
await sandbox.exec(["sh", "-c", "wc -w < /work/input.txt > /work/count.txt"]).complete()
print(await sandbox.read_text("work/count.txt"))

write_file writes a whole file, a string as UTF-8 or bytes, and its parent directory must exist; create_dir_all makes it and its parents, as mkdir -p. read_text reads a whole UTF-8 file, and read_file reads bytes, all of them or a range from an offset.

Look around

read_dir lists a directory, each entry with its name and metadata. stat_file answers what is at a path: its size, when it was last modified, and its etag. exists, is_file and is_dir say whether anything, a file, or a directory is there.

for entry in await sandbox.read_dir("work"):
print(entry.name, entry.metadata.size)
if await sandbox.is_file("work/count.txt"):
meta = await sandbox.stat_file("work/count.txt")
print(meta.size, meta.etag)

Move, copy, and remove

rename_file moves a file or a directory, and copy_file copies one with everything in it. Both refuse a destination that already exists unless overwrite is set. remove_file removes a file, or a directory with everything in it, and refuses a missing path unless missing_ok is set, as rm -f.

await sandbox.copy_file("work/count.txt", "work/count.bak")
await sandbox.rename_file("work/count.bak", "work/old.txt", overwrite=True)
await sandbox.remove_file("work", missing_ok=True)

Write only if unchanged

Pass a file’s etag from stat_file as if_match to write_file, and the write goes through only while the file still has that tag. If something changed it in between, the write is refused with 412, and nothing is overwritten. Of two such writes sent at once with one tag, one goes through and the other is refused with 412: read the file again and retry. The tag is checked before the content is written, and again once all of it has arrived, just before it replaces the file.

Reading while the sandbox is stopped

A sandbox’s files are read through its VM, which is booted again if it had been stopped for being unused. To read the output of a task that is done with no VM at all, have the task write it to a volume and read it from there instead; see Mounting volumes.