API Reference

watchdog.events

module

watchdog.events

synopsis

File system events and event handlers.

author

yesudeep@google.com (Yesudeep Mangalapilly)

author

contact@tiger-222.fr (Mickaël Schoentgen)

Event Classes

class watchdog.events.FileSystemEvent(src_path)[source]

Bases: object

Immutable type that represents a file system event that is triggered when a change occurs on the monitored file system.

All FileSystemEvent objects are required to be immutable and hence can be used as keys in dictionaries or be added to sets.

event_type = None

The type of the event as a string.

is_directory = False

True if event was emitted for a directory; False otherwise.

is_synthetic = False

True if event was synthesized; False otherwise.

These are events that weren’t actually broadcast by the OS, but are presumed to have happened based on other, actual events.

property src_path

Source path of the file system object that triggered this event.

class watchdog.events.FileSystemMovedEvent(src_path, dest_path)[source]

Bases: FileSystemEvent

File system event representing any kind of file system movement.

property dest_path

The destination path of the move event.

event_type = 'moved'

The type of the event as a string.

class watchdog.events.FileMovedEvent(src_path, dest_path)[source]

Bases: FileSystemMovedEvent

File system event representing file movement on the file system.

class watchdog.events.DirMovedEvent(src_path, dest_path)[source]

Bases: FileSystemMovedEvent

File system event representing directory movement on the file system.

is_directory = True

True if event was emitted for a directory; False otherwise.

class watchdog.events.FileModifiedEvent(src_path)[source]

Bases: FileSystemEvent

File system event representing file modification on the file system.

event_type = 'modified'

The type of the event as a string.

class watchdog.events.DirModifiedEvent(src_path)[source]

Bases: FileSystemEvent

File system event representing directory modification on the file system.

event_type = 'modified'

The type of the event as a string.

is_directory = True

True if event was emitted for a directory; False otherwise.

class watchdog.events.FileCreatedEvent(src_path)[source]

Bases: FileSystemEvent

File system event representing file creation on the file system.

event_type = 'created'

The type of the event as a string.

class watchdog.events.FileClosedEvent(src_path)[source]

Bases: FileSystemEvent

File system event representing file close on the file system.

event_type = 'closed'

The type of the event as a string.

class watchdog.events.DirCreatedEvent(src_path)[source]

Bases: FileSystemEvent

File system event representing directory creation on the file system.

event_type = 'created'

The type of the event as a string.

is_directory = True

True if event was emitted for a directory; False otherwise.

class watchdog.events.FileDeletedEvent(src_path)[source]

Bases: FileSystemEvent

File system event representing file deletion on the file system.

event_type = 'deleted'

The type of the event as a string.

class watchdog.events.DirDeletedEvent(src_path)[source]

Bases: FileSystemEvent

File system event representing directory deletion on the file system.

event_type = 'deleted'

The type of the event as a string.

is_directory = True

True if event was emitted for a directory; False otherwise.

Event Handler Classes

class watchdog.events.FileSystemEventHandler[source]

Bases: object

Base file system event handler that you can override methods from.

dispatch(event)[source]

Dispatches events to the appropriate methods.

Parameters

event (FileSystemEvent) – The event object representing the file system event.

on_any_event(event)[source]

Catch-all event handler.

Parameters

event (FileSystemEvent) – The event object representing the file system event.

on_closed(event)[source]

Called when a file opened for writing is closed.

Parameters

event (FileClosedEvent) – Event representing file closing.

on_created(event)[source]

Called when a file or directory is created.

Parameters

event (DirCreatedEvent or FileCreatedEvent) – Event representing file/directory creation.

on_deleted(event)[source]

Called when a file or directory is deleted.

Parameters

event (DirDeletedEvent or FileDeletedEvent) – Event representing file/directory deletion.

on_modified(event)[source]

Called when a file or directory is modified.

Parameters

event (DirModifiedEvent or FileModifiedEvent) – Event representing file/directory modification.

on_moved(event)[source]

Called when a file or a directory is moved or renamed.

Parameters

event (DirMovedEvent or FileMovedEvent) – Event representing file/directory movement.

class watchdog.events.PatternMatchingEventHandler(patterns=None, ignore_patterns=None, ignore_directories=False, case_sensitive=False)[source]

Bases: FileSystemEventHandler

Matches given patterns with file paths associated with occurring events.

property case_sensitive

(Read-only) True if path names should be matched sensitive to case; False otherwise.

dispatch(event)[source]

Dispatches events to the appropriate methods.

Parameters

event (FileSystemEvent) – The event object representing the file system event.

property ignore_directories

(Read-only) True if directories should be ignored; False otherwise.

property ignore_patterns

(Read-only) Patterns to ignore matching event paths.

property patterns

(Read-only) Patterns to allow matching event paths.

class watchdog.events.RegexMatchingEventHandler(regexes=None, ignore_regexes=None, ignore_directories=False, case_sensitive=False)[source]

Bases: FileSystemEventHandler

Matches given regexes with file paths associated with occurring events.

property case_sensitive

(Read-only) True if path names should be matched sensitive to case; False otherwise.

dispatch(event)[source]

Dispatches events to the appropriate methods.

Parameters

event (FileSystemEvent) – The event object representing the file system event.

property ignore_directories

(Read-only) True if directories should be ignored; False otherwise.

property ignore_regexes

(Read-only) Regexes to ignore matching event paths.

property regexes

(Read-only) Regexes to allow matching event paths.

class watchdog.events.LoggingEventHandler(logger=None)[source]

Bases: FileSystemEventHandler

Logs all the events captured.

on_created(event)[source]

Called when a file or directory is created.

Parameters

event (DirCreatedEvent or FileCreatedEvent) – Event representing file/directory creation.

on_deleted(event)[source]

Called when a file or directory is deleted.

Parameters

event (DirDeletedEvent or FileDeletedEvent) – Event representing file/directory deletion.

on_modified(event)[source]

Called when a file or directory is modified.

Parameters

event (DirModifiedEvent or FileModifiedEvent) – Event representing file/directory modification.

on_moved(event)[source]

Called when a file or a directory is moved or renamed.

Parameters

event (DirMovedEvent or FileMovedEvent) – Event representing file/directory movement.

watchdog.observers.api

Immutables

class watchdog.observers.api.ObservedWatch(path, recursive)[source]

Bases: object

An scheduled watch.

Parameters
  • path – Path string.

  • recursiveTrue if watch is recursive; False otherwise.

property is_recursive

Determines whether subdirectories are watched for the path.

property path

The path that this watch monitors.

Collections

class watchdog.observers.api.EventQueue(maxsize=0)[source]

Bases: SkipRepeatsQueue

Thread-safe event queue based on a special queue that skips adding the same event (FileSystemEvent) multiple times consecutively. Thus avoiding dispatching multiple event handling calls when multiple identical events are produced quicker than an observer can consume them.

Classes

class watchdog.observers.api.EventEmitter(event_queue, watch, timeout=1)[source]

Bases: BaseThread

Producer thread base class subclassed by event emitters that generate events and populate a queue with them.

Parameters
  • event_queue (watchdog.events.EventQueue) – The event queue to populate with generated events.

  • watch (ObservedWatch) – The watch to observe and produce events for.

  • timeout (float) – Timeout (in seconds) between successive attempts at reading events.

queue_event(event)[source]

Queues a single event.

Parameters

event (An instance of watchdog.events.FileSystemEvent or a subclass.) – Event to be queued.

queue_events(timeout)[source]

Override this method to populate the event queue with events per interval period.

Parameters

timeout (float) – Timeout (in seconds) between successive attempts at reading events.

run()[source]

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

property timeout

Blocking timeout for reading events.

property watch

The watch associated with this emitter.

class watchdog.observers.api.EventDispatcher(timeout=1)[source]

Bases: BaseThread

Consumer thread base class subclassed by event observer threads that dispatch events from an event queue to appropriate event handlers.

Parameters

timeout (float) – Timeout value (in seconds) passed to emitters constructions in the child class BaseObserver.

dispatch_events(event_queue)[source]

Override this method to consume events from an event queue, blocking on the queue for the specified timeout before raising queue.Empty.

Parameters

event_queue (EventQueue) – Event queue to populate with one set of events.

Raises

queue.Empty

property event_queue

The event queue which is populated with file system events by emitters and from which events are dispatched by a dispatcher thread.

run()[source]

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

stop()[source]

Signals the thread to stop.

property timeout

Timeout value to construct emitters with.

class watchdog.observers.api.BaseObserver(emitter_class, timeout=1)[source]

Bases: EventDispatcher

Base observer.

add_handler_for_watch(event_handler, watch)[source]

Adds a handler for the given watch.

Parameters
  • event_handler (watchdog.events.FileSystemEventHandler or a subclass) – An event handler instance that has appropriate event handling methods which will be called by the observer in response to file system events.

  • watch (An instance of ObservedWatch or a subclass of ObservedWatch) – The watch to add a handler for.

dispatch_events(event_queue)[source]

Override this method to consume events from an event queue, blocking on the queue for the specified timeout before raising queue.Empty.

Parameters

event_queue (EventQueue) – Event queue to populate with one set of events.

Raises

queue.Empty

property emitters

Returns event emitter created by this observer.

on_thread_stop()[source]

Override this method instead of stop(). stop() calls this method.

This method is called immediately after the thread is signaled to stop.

remove_handler_for_watch(event_handler, watch)[source]

Removes a handler for the given watch.

Parameters
  • event_handler (watchdog.events.FileSystemEventHandler or a subclass) – An event handler instance that has appropriate event handling methods which will be called by the observer in response to file system events.

  • watch (An instance of ObservedWatch or a subclass of ObservedWatch) – The watch to remove a handler for.

schedule(event_handler, path, recursive=False)[source]

Schedules watching a path and calls appropriate methods specified in the given event handler in response to file system events.

Parameters
  • event_handler (watchdog.events.FileSystemEventHandler or a subclass) – An event handler instance that has appropriate event handling methods which will be called by the observer in response to file system events.

  • path (str) – Directory path that will be monitored.

  • recursive (bool) – True if events will be emitted for sub-directories traversed recursively; False otherwise.

Returns

An ObservedWatch object instance representing a watch.

start()[source]

Start the thread’s activity.

It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

This method will raise a RuntimeError if called more than once on the same thread object.

unschedule(watch)[source]

Unschedules a watch.

Parameters

watch (An instance of ObservedWatch or a subclass of ObservedWatch) – The watch to unschedule.

unschedule_all()[source]

Unschedules all watches and detaches all associated event handlers.

watchdog.observers

module

watchdog.observers

synopsis

Observer that picks a native implementation if available.

author

yesudeep@google.com (Yesudeep Mangalapilly)

author

contact@tiger-222.fr (Mickaël Schoentgen)

Classes

watchdog.observers.Observer

alias of InotifyObserver

Observer thread that schedules watching directories and dispatches calls to event handlers.

You can also import platform specific classes directly and use it instead of Observer. Here is a list of implemented observer classes.:

Class

Platforms

Note

inotify.InotifyObserver

Linux 2.6.13+

inotify(7) based observer

fsevents.FSEventsObserver

macOS

FSEvents based observer

kqueue.KqueueObserver

macOS and BSD with kqueue(2)

kqueue(2) based observer

read_directory_changes.WindowsApiObserver

MS Windows

Windows API-based observer

polling.PollingObserver

Any

fallback implementation

watchdog.observers.polling

module

watchdog.observers.polling

synopsis

Polling emitter implementation.

author

yesudeep@google.com (Yesudeep Mangalapilly)

author

contact@tiger-222.fr (Mickaël Schoentgen)

Classes

class watchdog.observers.polling.PollingObserver(timeout=1)[source]

Bases: BaseObserver

Platform-independent observer that polls a directory to detect file system changes.

class watchdog.observers.polling.PollingObserverVFS(stat, listdir, polling_interval=1)[source]

Bases: BaseObserver

File system independent observer that polls a directory to detect changes.

__init__(stat, listdir, polling_interval=1)[source]
Parameters
  • stat – stat function. See os.stat for details.

  • listdir – listdir function. See os.scandir for details.

  • polling_interval (float) – interval in seconds between polling the file system.

watchdog.utils

module

watchdog.utils

synopsis

Utility classes and functions.

author

yesudeep@google.com (Yesudeep Mangalapilly)

author

contact@tiger-222.fr (Mickaël Schoentgen)

Classes

class watchdog.utils.BaseThread[source]

Bases: Thread

Convenience class for creating stoppable threads.

property daemon

A boolean value indicating whether this thread is a daemon thread.

This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

The entire Python program exits when only daemon threads are left.

getName()

Return a string used for identification purposes only.

This method is deprecated, use the name attribute instead.

property ident

Thread identifier of this thread or None if it has not been started.

This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited.

isDaemon()

Return whether this thread is a daemon.

This method is deprecated, use the daemon attribute instead.

is_alive()

Return whether the thread is alive.

This method returns True just before the run() method starts until just after the run() method terminates. See also the module function enumerate().

join(timeout=None)

Wait until the thread terminates.

This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

When the timeout argument is not present or None, the operation will block until the thread terminates.

A thread can be join()ed many times.

join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.

property name

A string used for identification purposes only.

It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.

property native_id

Native integral thread ID of this thread, or None if it has not been started.

This is a non-negative integer. See the get_native_id() function. This represents the Thread ID as reported by the kernel.

on_thread_start()[source]

Override this method instead of start(). start() calls this method.

This method is called right before this thread is started and this object’s run() method is invoked.

on_thread_stop()[source]

Override this method instead of stop(). stop() calls this method.

This method is called immediately after the thread is signaled to stop.

run()

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

setDaemon(daemonic)

Set whether this thread is a daemon.

This method is deprecated, use the .daemon property instead.

setName(name)

Set the name string for this thread.

This method is deprecated, use the name attribute instead.

should_keep_running()[source]

Determines whether the thread should continue running.

start()[source]

Start the thread’s activity.

It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

This method will raise a RuntimeError if called more than once on the same thread object.

stop()[source]

Signals the thread to stop.

watchdog.utils.dirsnapshot

module

watchdog.utils.dirsnapshot

synopsis

Directory snapshots and comparison.

author

yesudeep@google.com (Yesudeep Mangalapilly)

author

contact@tiger-222.fr (Mickaël Schoentgen)

Where are the moved events? They ‘disappeared’

This implementation does not take partition boundaries into consideration. It will only work when the directory tree is entirely on the same file system. More specifically, any part of the code that depends on inode numbers can break if partition boundaries are crossed. In these cases, the snapshot diff will represent file/directory movement as created and deleted events.

Classes

class watchdog.utils.dirsnapshot.DirectorySnapshot(path, recursive=True, stat=<built-in function stat>, listdir=<built-in function scandir>)[source]

Bases: object

A snapshot of stat information of files in a directory.

Parameters
  • path (str) – The directory path for which a snapshot should be taken.

  • recursive (bool) – True if the entire directory tree should be included in the snapshot; False otherwise.

  • stat

    Use custom stat function that returns a stat structure for path. Currently only st_dev, st_ino, st_mode and st_mtime are needed.

    A function taking a path as argument which will be called for every entry in the directory tree.

  • listdir – Use custom listdir function. For details see os.scandir.

inode(path)[source]

Returns an id for path.

path(id)[source]

Returns path for id. None if id is unknown to this snapshot.

property paths

Set of file/directory paths in the snapshot.

stat_info(path)[source]

Returns a stat information object for the specified path from the snapshot.

Attached information is subject to change. Do not use unless you specify stat in constructor. Use inode(), mtime(), isdir() instead.

Parameters

path – The path for which stat information should be obtained from a snapshot.

class watchdog.utils.dirsnapshot.DirectorySnapshotDiff(ref, snapshot, ignore_device=False)[source]

Bases: object

Compares two directory snapshots and creates an object that represents the difference between the two snapshots.

Parameters
  • ref (DirectorySnapshot) – The reference directory snapshot.

  • snapshot (DirectorySnapshot) – The directory snapshot which will be compared with the reference snapshot.

  • ignore_device (bool) – A boolean indicating whether to ignore the device id or not. By default, a file may be uniquely identified by a combination of its first inode and its device id. The problem is that the device id may (or may not) change between system boots. This problem would cause the DirectorySnapshotDiff to think a file has been deleted and created again but it would be the exact same file. Set to True only if you are sure you will always use the same device.

property dirs_created

List of directories that were created.

property dirs_deleted

List of directories that were deleted.

property dirs_modified

List of directories that were modified.

property dirs_moved

List of directories that were moved.

Each event is a two-tuple the first item of which is the path that has been renamed to the second item in the tuple.

property files_created

List of files that were created.

property files_deleted

List of files that were deleted.

property files_modified

List of files that were modified.

property files_moved

List of files that were moved.

Each event is a two-tuple the first item of which is the path that has been renamed to the second item in the tuple.

class watchdog.utils.dirsnapshot.EmptyDirectorySnapshot[source]

Bases: object

Class to implement an empty snapshot. This is used together with DirectorySnapshot and DirectorySnapshotDiff in order to get all the files/folders in the directory as created.

static path(_)[source]

Mock up method to return the path of the received inode. As the snapshot is intended to be empty, it always returns None.

Returns

None.

property paths

Mock up method to return a set of file/directory paths in the snapshot. As the snapshot is intended to be empty, it always returns an empty set.

Returns

An empty set.

watchdog.tricks

module

watchdog.tricks

synopsis

Utility event handlers.

author

yesudeep@google.com (Yesudeep Mangalapilly)

author

contact@tiger-222.fr (Mickaël Schoentgen)

Classes

class watchdog.tricks.Trick(patterns=None, ignore_patterns=None, ignore_directories=False, case_sensitive=False)[source]

Bases: PatternMatchingEventHandler

Your tricks should subclass this class.

class watchdog.tricks.LoggerTrick(patterns=None, ignore_patterns=None, ignore_directories=False, case_sensitive=False)[source]

Bases: Trick

A simple trick that does only logs events.

on_any_event(event)[source]

Catch-all event handler.

Parameters

event (FileSystemEvent) – The event object representing the file system event.

on_created(event)[source]

Called when a file or directory is created.

Parameters

event (DirCreatedEvent or FileCreatedEvent) – Event representing file/directory creation.

on_deleted(event)[source]

Called when a file or directory is deleted.

Parameters

event (DirDeletedEvent or FileDeletedEvent) – Event representing file/directory deletion.

on_modified(event)[source]

Called when a file or directory is modified.

Parameters

event (DirModifiedEvent or FileModifiedEvent) – Event representing file/directory modification.

on_moved(event)[source]

Called when a file or a directory is moved or renamed.

Parameters

event (DirMovedEvent or FileMovedEvent) – Event representing file/directory movement.

class watchdog.tricks.ShellCommandTrick(shell_command=None, patterns=None, ignore_patterns=None, ignore_directories=False, wait_for_process=False, drop_during_process=False)[source]

Bases: Trick

Executes shell commands in response to matched events.

on_any_event(event)[source]

Catch-all event handler.

Parameters

event (FileSystemEvent) – The event object representing the file system event.

class watchdog.tricks.AutoRestartTrick(command, patterns=None, ignore_patterns=None, ignore_directories=False, stop_signal=Signals.SIGINT, kill_after=10)[source]

Bases: Trick

Starts a long-running subprocess and restarts it on matched events.

The command parameter is a list of command arguments, such as [‘bin/myserver’, ‘-c’, ‘etc/myconfig.ini’].

Call start() after creating the Trick. Call stop() when stopping the process.

on_any_event(event)[source]

Catch-all event handler.

Parameters

event (FileSystemEvent) – The event object representing the file system event.