Repository navigation
Example Watching Folders
examples/watch/watch_folder.py shows a folder that another program changes. It needs the watch extra (watchdog), which uses the system's own notifications (inotify on Linux, ReadDirectoryChangesW on Windows): nothing is polled.
pip install "turboframe[watch] @ git+https://github.com/divengine/turboframe@v0.3.0"
python examples/watch/watch_folder.py [FOLDER]Then, from another terminal, create, rename or delete files in FOLDER.

It shows the same changes two ways:
-
The explorer (left) watches the folders it shows open, by itself. Only a folder whose entries changed is read again, and the bar and the scroll stay where they were. An application gets this from
ExplorerMixinwith the extra installed; see The Explorer. -
The log (right) is a
FolderWatcherof the example's own, on the folder and each of its subfolders. Every batch of changes it reports is one line.

from turboframe.watch import Batch, FolderWatcher
self.watcher = FolderWatcher(self.changed_elsewhere, self.refused_elsewhere)
self.watch_folders()
def watch_folders(self) -> None:
"""Watch the folder and every subfolder (FolderWatcher watches each one alone, up to MAX_WATCHED)."""
folders = [self.folder, *(p for p in sorted(self.folder.rglob("*")) if p.is_dir() and ".git" not in p.parts)]
self.watcher.set_folders(folders)-
FolderWatcher(on_change, on_error)watches folders one by one, not recursively;set_folders(folders)says which, and adds and drops watches to match. - A burst of changes comes as one
Batch(the folders whose entries changed), after a short delay. Too many changes at once come asbatch.everything: read every watched folder again. - Only entries count: a file written in place is not a change of the tree.
The callbacks run on watchdog's thread. The application moves them to its own with call_from_thread before it touches a widget:
# watchdog's thread: hand over to the application's
def changed_elsewhere(self, batch: Batch) -> None:
self.call_from_thread(self.show_batch, batch)
def refused_elsewhere(self, folder: Path, why: str) -> None:
self.call_from_thread(self.note, f"cannot watch {folder}: {why}")
# the application's thread
def show_batch(self, batch: Batch) -> None:
if batch.everything:
self.note("many changes at once: everything is read again")
else:
...
self.watch_folders() # a new subfolder is watched too, a deleted one droppedThe watcher stops with the application:
async def on_unmount(self) -> None:
if self.watcher is not None:
self.watcher.stop()Without watchdog the example says which extra to install, and stops. See Files for FolderWatcher's options (the delay, the limits, a stand-in observer for tests).
TurboFrame · part of Divengine · GPL-3.0-or-later · report an issue
Tutorial
Examples
The desktop
- The Desktop
- Application Mixins
- Windows and Lists
- Dialogs
- Histories
- Progress
- Themes and Colors
- Glyphs
- Settings and Recent Files
- Command Palette
Editing
Tasks
Languages
Running
Reference
Links