# Watch Directory for Changes
<subtitle>Monitor file change events in sandbox directories in real-time.</subtitle>

You can use the `files.watch_dir()` method to monitor directory changes.

## Environment Setup

Before using the SDK, please ensure that the `AGENTBOX_API_KEY` environment variable is configured.

>
> You can obtain your API key from the [Console API Keys page](https://console.ucloud.cn/modelverse/experience/api-keys).

```bash
export AGENTBOX_API_KEY=your_api_key
```

> **Tip**
>
> Since events are tracked asynchronously, delivery may be delayed.
> It is recommended not to collect or close the watcher immediately after making changes.

```python
from ucloud_sandbox import Sandbox, FilesystemEventType

sandbox = Sandbox.create()
dirname = '/home/user'

# Watch directory changes
handle = sandbox.files.watch_dir(dirname)
# Trigger file write event
sandbox.files.write(f"{dirname}/my-file", "hello")

# Get the latest events since the last `get_new_events()` call
events = handle.get_new_events()
for event in events:
    print(event)
    if event.type == FilesystemEventType.WRITE:
        print(f"wrote to file {event.name}")
```

## Recursive Watching

You can enable recursive watching through the `recursive` parameter.

> **Tip**
>
> When quickly creating new folders (e.g., deeply nested folder paths), events other than `CREATE` may not be triggered. To avoid this, create the required folder structure in advance.

```python
from ucloud_sandbox import Sandbox, FilesystemEventType

sandbox = Sandbox.create()
dirname = '/home/user'

# Watch directory changes (recursive)
handle = sandbox.files.watch_dir(dirname, recursive=True)
# Trigger file write event
sandbox.files.write(f"{dirname}/my-folder/my-file", "hello")

# Get the latest events since the last `get_new_events()` call
events = handle.get_new_events()
for event in events:
    print(event)
    if event.type == FilesystemEventType.WRITE:
        print(f"wrote to file {event.name}")
```
