> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreweave.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Cleanup

> Terminate sandboxes and manage cleanup with context managers, explicit stops, and global atexit handlers.

<Note>
  The examples on this page omit `auth`. To authenticate with your W\&B API key, install `cwsandbox[wandb]` and pass `auth=AuthStrategy.WANDB` to `Sandbox.run()`, `Sandbox()`, or `Sandbox.session()`. See [Get started](/products/sandboxes/serverless/get-started).
</Note>

This page shows how to terminate sandboxes reliably so resources are released when your code finishes or exits unexpectedly. Use these patterns to avoid leaving orphaned sandboxes running after your script completes.

Use a context manager to handle cleanup automatically:

```python theme={"system"}
with Sandbox.run() as sandbox:
    sandbox.exec(["echo", "hello"]).result()
# Stopped automatically
```

For sandboxes created without a context manager, call `.stop()` explicitly:

```python theme={"system"}
sandbox = Sandbox.run()
sandbox.exec(["echo", "hello"]).result()
sandbox.stop().result()
```

As a safety net, the SDK registers global cleanup handlers for `atexit` and signals (Ctrl+C, `SIGTERM`). These handlers stop sandboxes that belong to a [`Session`](../guides/sessions), so session-managed sandboxes stop even on unexpected exits. A sandbox created directly with `Sandbox.run()` isn't part of a session, so it keeps running after the process exits until you stop it or its lifetime expires. See [Set up Claude Code with the Sandbox SDK](../../agents/claude-code#set-up-with-the-sandbox-sdk) for a workflow that relies on this.

For batch cleanup, tagging strategies, and orphan recovery, see the [Cleanup patterns guide](../guides/cleanup-patterns).


## Related topics

- [Cleanup](/products/sandboxes/client/tutorial/cleanup.md)
