gws.lib.watcher¶
File system watcher.
Monitors file system events (creation, deletion, modification and movement) using watchdog,
and calls a notification callback when an event occurs on a watched path.
A Watcher can watch whole directories, optionally recursively and restricted to file names
matching a regular expression, and individual files. Paths matching an exclude pattern are ignored.
The callback is called from the observer thread, not from the thread that started the watcher.
Example:
import gws.lib.watcher
def on_change(event_type, path):
print(event_type, path)
w = gws.lib.watcher.new(on_change)
w.add_directory('/data/config', file_pattern=r'[.]json$', recursive=True)
w.add_file('/data/config.cx')
w.exclude(r'/[.]git/')
w.start()
...
w.stop()
Source code: gws.lib.watcher
Package Contents¶
- gws.lib.watcher.new(notify: _NotifyFn)¶
Create a new watcher.
- Parameters:
notify – A callback function that will be called when an event occurs. It accepts two arguments: the event type and the path of the file. The callback is called from a different thread than the one that created the watcher.
- Returns:
The watcher, not started yet.
- class gws.lib.watcher.Watcher(notify: _NotifyFn)¶
File system watcher.
- dirEntries¶
- excludePatterns = []¶
- filePaths¶
- notify¶
- observer: watchdog.observers.Observer | None¶
The
watchdogobserver, created bystart.Nonebeforestart.
- add_directory(dirname: str | os.PathLike, file_pattern: str = '', recursive: bool = False)¶
Add a directory to watch.
- Parameters:
dirname – Directory path.
file_pattern – Regular expression to search for in file names. If empty, all files match.
recursive – Also watch subdirectories.
- exclude(path_pattern: str)¶
Exclude paths from watching.
- Parameters:
path_pattern – Regular expression to search for in the full path.
- path_matches(path)¶
Check if a path is watched.
A path is watched if it is not excluded, and is either an added file or a file in an added directory whose name matches the directory’s file pattern.
- Parameters:
path – File path.
- Returns:
Trueif the path is watched.
- register(ev: watchdog.events.FileSystemEvent)¶
Handle a file system event, calling the callback if the path is watched.
- Parameters:
ev – The event.
- start()¶
Start watching the added directories and files in a background thread.
- stop()¶
Stop watching and wait for the observer thread to finish.