Watch for Changes

Updated at:

Filesystem supports watching a directory for changes. This is useful for waiting for agent output files in long tasks, syncing artifacts generated by programs inside the sandbox, or forwarding file change events to a business-side state machine.

Watch a directory

TypeScript

In the TypeScript SDK, onEvent is the second positional argument to watchDir(), not a field inside an options object. Optional settings such as recursive and onExit are passed through the third argument. Stop watching with watcher.stop().

import { Sandbox } from "e2b";

const sandbox = await Sandbox.create("code-interpreter-v1");

try {
  // watchDir requires the directory to exist. Create the directory before you start watching.
  await sandbox.files.makeDir("/tmp/output");

  const watcher = await sandbox.files.watchDir("/tmp/output", (event) => {
    console.log(event);
  });

  // Stop watching after the task finishes.
  await watcher.stop();
} finally {
  // Release the sandbox on both success and failure, instead of waiting for it to be recycled on timeout.
  await sandbox.kill();
}

Python

The Python SDK provides the callback form of watch_dir() only in its async API, so the example uses AsyncSandbox . Pass the callback as the positional on_event argument:

import asyncio

from e2b_code_interpreter import AsyncSandbox


async def main():
    sandbox = await AsyncSandbox.create("code-interpreter-v1")
    try:
        # watch_dir requires the directory to exist. Otherwise it reports path not found, so create the directory before you start watching.
        await sandbox.files.make_dir("/tmp/output")

        handle = await sandbox.files.watch_dir(
            "/tmp/output",
            lambda event: print(event),
        )

        # Stop watching after the task finishes.
        await handle.stop()
    finally:
        # Release the sandbox on both success and failure, instead of waiting for it to be recycled on timeout.
        await sandbox.kill()


asyncio.run(main())

Before production use, validate the event shape, stop behavior, and error responses with a minimal example.

Recommendations

  • Make sure the directory exists before watching it. Create the output directory with sandbox.files.makeDir() (TypeScript) or sandbox.files.make_dir() (Python).

  • The callback may receive duplicate events. Deduplicate on the business side by file path, event type, and task ID.

  • Watching helps deliver changes sooner, but the final task state should still be determined from the command exit code, a business state file, or external task state.

  • For long-running watchers, set an application-level timeout and stop the watcher when the task succeeds, fails, or times out.

  • If you only need to wait for a single file to appear, use bounded polling with sandbox.files.exists().