logo
Free, unlimited AI code reviews that run on commit
git-lrc git-lrc GitHub Install Now We'd appreciate a star git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt

watchdog - watchdog Documentation

Api Reference

watchdog.eventsmodule watchdog.events

       synopsis
              File system events and event handlers.

       authoryesudeep@google.com (Yesudeep Mangalapilly)

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

   EventClassesclasswatchdog.events.FileSystemEvent(src_path:bytes|str,dest_path:bytes|str='',is_synthetic:bool=False)
              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.

              is_directory:bool=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.

       classwatchdog.events.FileSystemMovedEvent(src_path:bytes|str,dest_path:bytes|str='',is_synthetic:bool=False)
              Bases: FileSystemEvent

              File system event representing any kind of file system movement.

       classwatchdog.events.FileMovedEvent(src_path:bytes|str,dest_path:bytes|str='',is_synthetic:bool=False)
              Bases: FileSystemMovedEvent

              File system event representing file movement on the file system.

       classwatchdog.events.DirMovedEvent(src_path:bytes|str,dest_path:bytes|str='',is_synthetic:bool=False)
              Bases: FileSystemMovedEvent

              File system event representing directory movement on the file system.

              is_directory:bool=True
                     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.

       classwatchdog.events.FileModifiedEvent(src_path:bytes|str,dest_path:bytes|str='',is_synthetic:bool=False)
              Bases: FileSystemEvent

              File system event representing file modification on the file system.

       classwatchdog.events.DirModifiedEvent(src_path:bytes|str,dest_path:bytes|str='',is_synthetic:bool=False)
              Bases: FileSystemEvent

              File system event representing directory modification on the file system.

              is_directory:bool=True
                     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.

       classwatchdog.events.FileCreatedEvent(src_path:bytes|str,dest_path:bytes|str='',is_synthetic:bool=False)
              Bases: FileSystemEvent

              File system event representing file creation on the file system.

       classwatchdog.events.FileClosedEvent(src_path:bytes|str,dest_path:bytes|str='',is_synthetic:bool=False)
              Bases: FileSystemEvent

              File system event representing file close on the file system.

       classwatchdog.events.FileClosedNoWriteEvent(src_path:bytes|str,dest_path:bytes|str='',is_synthetic:bool=False)
              Bases: FileSystemEvent

              File system event representing an unmodified file close on the file system.

       classwatchdog.events.FileOpenedEvent(src_path:bytes|str,dest_path:bytes|str='',is_synthetic:bool=False)
              Bases: FileSystemEvent

              File system event representing file close on the file system.

       classwatchdog.events.DirCreatedEvent(src_path:bytes|str,dest_path:bytes|str='',is_synthetic:bool=False)
              Bases: FileSystemEvent

              File system event representing directory creation on the file system.

              is_directory:bool=True
                     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.

       classwatchdog.events.FileDeletedEvent(src_path:bytes|str,dest_path:bytes|str='',is_synthetic:bool=False)
              Bases: FileSystemEvent

              File system event representing file deletion on the file system.

       classwatchdog.events.DirDeletedEvent(src_path:bytes|str,dest_path:bytes|str='',is_synthetic:bool=False)
              Bases: FileSystemEvent

              File system event representing directory deletion on the file system.

              is_directory:bool=True
                     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.

   EventHandlerClassesclasswatchdog.events.FileSystemEventHandler
              Bases: object

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

              dispatch(event:FileSystemEvent)->None
                     Dispatches events to the appropriate methods.

                     Parametersevent (FileSystemEvent) -- The event object representing the file system event.

              on_any_event(event:FileSystemEvent)->None
                     Catch-all event handler.

                     Parametersevent (FileSystemEvent) -- The event object representing the file system event.

              on_closed(event:FileClosedEvent)->None
                     Called when a file opened for writing is closed.

                     Parametersevent (FileClosedEvent) -- Event representing file closing.

              on_closed_no_write(event:FileClosedNoWriteEvent)->None
                     Called when a file opened for reading is closed.

                     Parametersevent (FileClosedNoWriteEvent) -- Event representing file closing.

              on_created(event:DirCreatedEvent|FileCreatedEvent)->None
                     Called when a file or directory is created.

                     Parametersevent (DirCreatedEvent or FileCreatedEvent)  --  Event  representing  file/directory
                            creation.

              on_deleted(event:DirDeletedEvent|FileDeletedEvent)->None
                     Called when a file or directory is deleted.

                     Parametersevent  (DirDeletedEvent  or  FileDeletedEvent)  -- Event representing file/directory
                            deletion.

              on_modified(event:DirModifiedEvent|FileModifiedEvent)->None
                     Called when a file or directory is modified.

                     Parametersevent (DirModifiedEvent or FileModifiedEvent) -- Event  representing  file/directory
                            modification.

              on_moved(event:DirMovedEvent|FileMovedEvent)->None
                     Called when a file or a directory is moved or renamed.

                     Parametersevent   (DirMovedEvent  or  FileMovedEvent)  --  Event  representing  file/directory
                            movement.

              on_opened(event:FileOpenedEvent)->None
                     Called when a file is opened.

                     Parametersevent (FileOpenedEvent) -- Event representing file opening.

       classwatchdog.events.PatternMatchingEventHandler(*,patterns:list[str]|None=None,ignore_patterns:list[str]|None=None,ignore_directories:bool=False,case_sensitive:bool=False)
              Bases: FileSystemEventHandler

              Matches given  patterns  with  file  paths  associated  with  occurring  events.   Uses  pathlib's
              PurePath.match() method. patterns and ignore_patterns are expected to be a list of strings.

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

              dispatch(event:FileSystemEvent)->None
                     Dispatches events to the appropriate methods.

                     Parametersevent (FileSystemEvent) -- The event object representing the file system event.

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

              propertyignore_patterns:list[str]|None
                     (Read-only) Patterns to ignore matching event paths.

              propertypatterns:list[str]|None
                     (Read-only) Patterns to allow matching event paths.

       classwatchdog.events.RegexMatchingEventHandler(*,regexes:list[str]|None=None,ignore_regexes:list[str]|None=None,ignore_directories:bool=False,case_sensitive:bool=False)
              Bases: FileSystemEventHandler

              Matches given regexes with file paths associated with occurring events.  Uses the re module.

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

              dispatch(event:FileSystemEvent)->None
                     Dispatches events to the appropriate methods.

                     Parametersevent (FileSystemEvent) -- The event object representing the file system event.

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

              propertyignore_regexes:list[Pattern[str]]
                     (Read-only) Regexes to ignore matching event paths.

              propertyregexes:list[Pattern[str]]
                     (Read-only) Regexes to allow matching event paths.

       classwatchdog.events.LoggingEventHandler(*,logger:Logger|None=None)
              Bases: FileSystemEventHandler

              Logs all the events captured.

              on_closed(event:FileClosedEvent)->None
                     Called when a file opened for writing is closed.

                     Parametersevent (FileClosedEvent) -- Event representing file closing.

              on_closed_no_write(event:FileClosedNoWriteEvent)->None
                     Called when a file opened for reading is closed.

                     Parametersevent (FileClosedNoWriteEvent) -- Event representing file closing.

              on_created(event:DirCreatedEvent|FileCreatedEvent)->None
                     Called when a file or directory is created.

                     Parametersevent  (DirCreatedEvent  or  FileCreatedEvent)  -- Event representing file/directory
                            creation.

              on_deleted(event:DirDeletedEvent|FileDeletedEvent)->None
                     Called when a file or directory is deleted.

                     Parametersevent (DirDeletedEvent or FileDeletedEvent)  --  Event  representing  file/directory
                            deletion.

              on_modified(event:DirModifiedEvent|FileModifiedEvent)->None
                     Called when a file or directory is modified.

                     Parametersevent  (DirModifiedEvent  or FileModifiedEvent) -- Event representing file/directory
                            modification.

              on_moved(event:DirMovedEvent|FileMovedEvent)->None
                     Called when a file or a directory is moved or renamed.

                     Parametersevent  (DirMovedEvent  or  FileMovedEvent)  --  Event  representing   file/directory
                            movement.

              on_opened(event:FileOpenedEvent)->None
                     Called when a file is opened.

                     Parametersevent (FileOpenedEvent) -- Event representing file opening.

   watchdog.observers.apiImmutablesclasswatchdog.observers.api.ObservedWatch(path:str|Path,*,recursive:bool,event_filter:list[type[FileSystemEvent]]|None=None)
              Bases: object

              An scheduled watch.

              Parameterspath -- Path string.

                     • recursive -- True if watch is recursive; False otherwise.

                     • event_filter -- Optional collection of watchdog.events.FileSystemEvent to watch

              propertyevent_filter:frozenset[type[FileSystemEvent]]|None
                     Collection of event types watched for the path

              propertyis_recursive:bool
                     Determines whether subdirectories are watched for the path.

              propertypath:str
                     The path that this watch monitors.

   Collectionsclasswatchdog.observers.api.EventQueue(maxsize=0)
              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.

   Classesclasswatchdog.observers.api.EventEmitter(event_queue:EventQueue,watch:ObservedWatch,*,timeout:float=1.0,event_filter:list[type[FileSystemEvent]]|None=None)
              Bases: BaseThread

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

              Parametersevent_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.

                     • event_filter (Iterable[watchdog.events.FileSystemEvent] | None) --  Collection  of  event
                       types to emit, or None for no filtering (default).

              queue_event(event:FileSystemEvent)->None
                     Queues a single event.

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

              queue_events(timeout:float)->None
                     Override this method to populate the event queue with events per interval period.

                     Parameterstimeout  (float)  --  Timeout  (in  seconds)  between successive attempts at reading
                            events.

              run()->None
                     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.

              propertytimeout:float
                     Blocking timeout for reading events.

              propertywatch:ObservedWatch
                     The watch associated with this emitter.

       classwatchdog.observers.api.EventDispatcher(*,timeout:float=1.0)
              Bases: BaseThread

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

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

              dispatch_events(event_queue:EventQueue)->None
                     Override this method to consume events from an event queue, blocking on the queue  for  the
                     specified timeout before raising queue.Empty.

                     Parametersevent_queue (EventQueue) -- Event queue to populate with one set of events.

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

              run()->None
                     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()->None
                     Signals the thread to stop.

              stop_event=<objectobject>
                     Event inserted into the queue to signal a requested stop.

              propertytimeout:float
                     Timeout value to construct emitters with.

       classwatchdog.observers.api.BaseObserver(emitter_class:type[EventEmitter],*,timeout:float=1.0)
              Bases: EventDispatcher

              Base observer.

              add_handler_for_watch(event_handler:FileSystemEventHandler,watch:ObservedWatch)->None
                     Adds a handler for the given watch.

                     Parametersevent_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:EventQueue)->None
                     Override  this  method to consume events from an event queue, blocking on the queue for the
                     specified timeout before raising queue.Empty.

                     Parametersevent_queue (EventQueue) -- Event queue to populate with one set of events.

                     Raisesqueue.Emptypropertyemitters:set[EventEmitter]
                     Returns event emitter created by this observer.

              on_thread_stop()->None
                     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:FileSystemEventHandler,watch:ObservedWatch)->None
                     Removes a handler for the given watch.

                     Parametersevent_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:FileSystemEventHandler,path:str,*,recursive:bool=False,event_filter:list[type[FileSystemEvent]]|None=None)->ObservedWatch
                     Schedules  watching  a  path  and  calls  appropriate  methods specified in the given event
                     handler in response to file system events.

                     Parametersevent_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.

                            • event_filter  (Iterable[watchdog.events.FileSystemEvent]  | None) -- Collection of
                              event types to emit, or None for no filtering (default).

                     Returns
                            An ObservedWatch object instance representing a watch.

              start()->None
                     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:ObservedWatch)->None
                     Unschedules a watch.

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

              unschedule_all()->None
                     Unschedules all watches and detaches all associated event handlers.

   watchdog.observersmodule watchdog.observers

       synopsis
              Observer that picks a native implementation if available.

       authoryesudeep@google.com (Yesudeep Mangalapilly)

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

   Classeswatchdog.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 │ Microsoft Windows            │ Windows API-based observer │
       ├───────────────────────────────────────────┼──────────────────────────────┼────────────────────────────┤
       │ polling.PollingObserver                   │ Any                          │ fallback implementation    │
       └───────────────────────────────────────────┴──────────────────────────────┴────────────────────────────┘

   watchdog.observers.pollingmodule watchdog.observers.polling

       synopsis
              Polling emitter implementation.

       authoryesudeep@google.com (Yesudeep Mangalapilly)

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

   Classesclasswatchdog.observers.polling.PollingObserver(*,timeout:float=1.0)
              Bases: BaseObserver

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

       classwatchdog.observers.polling.PollingObserverVFS(stat:Callable[[str],os.stat_result],listdir:Callable[[str|None],Iterator[os.DirEntry]],*,polling_interval:int=1)
              Bases: BaseObserver

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

              __init__(stat:Callable[[str],os.stat_result],listdir:Callable[[str|None],Iterator[os.DirEntry]],*,polling_interval:int=1)->NoneParametersstat -- stat function. See os.stat for details.

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

                            • polling_interval (int) -- interval in seconds between polling the file system.

   watchdog.utilsmodule watchdog.utils

       synopsis
              Utility classes and functions.

       authoryesudeep@google.com (Yesudeep Mangalapilly)

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

   Classesclasswatchdog.utils.BaseThread
              Bases: Thread

              Convenience class for creating stoppable threads.

              propertydaemon
                     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.

              propertyident
                     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.

              propertyname
                     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.

              propertynative_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()->None
                     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()->None
                     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()->bool
                     Determines whether the thread should continue running.

              start()->None
                     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()->None
                     Signals the thread to stop.

   watchdog.utils.dirsnapshotmodule watchdog.utils.dirsnapshot

       synopsis
              Directory snapshots and comparison.

       authoryesudeep@google.com (Yesudeep Mangalapilly)

       authorcontact@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.

   Classesclasswatchdog.utils.dirsnapshot.DirectorySnapshot(path:str,*,recursive:bool=True,stat:Callable[[str],os.stat_result]=<built-infunctionstat>,listdir:Callable[[str|None],Iterator[os.DirEntry]]=<built-infunctionscandir>)
              Bases: object

              A snapshot of stat information of files in a directory.

              Parameterspath (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:bytes|str)->tuple[int,int]
                     Returns an id for path.

              path(uid:tuple[int,int])->bytes|str|None
                     Returns path for id. None if id is unknown to this snapshot.

              propertypaths:set[bytes|str]
                     Set of file/directory paths in the snapshot.

              stat_info(path:bytes|str)->stat_result
                     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.

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

       classwatchdog.utils.dirsnapshot.DirectorySnapshotDiff(ref:DirectorySnapshot,snapshot:DirectorySnapshot,*,ignore_device:bool=False)
              Bases: object

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

              Parametersref (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.

              classContextManager(path:str,*,recursive:bool=True,stat:Callable[[str],os.stat_result]=<built-infunctionstat>,listdir:Callable[[str|None],Iterator[os.DirEntry]]=<built-infunctionscandir>,ignore_device:bool=False)
                     Bases: object

                     Context manager that creates two directory snapshots and a diff object that represents  the
                     difference between the two snapshots.

                     Parameterspath (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.

                            • 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.

              propertydirs_created:list[bytes|str]
                     List of directories that were created.

              propertydirs_deleted:list[bytes|str]
                     List of directories that were deleted.

              propertydirs_modified:list[bytes|str]
                     List of directories that were modified.

              propertydirs_moved:list[tuple[bytes|str,bytes|str]]
                     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.

              propertyfiles_created:list[bytes|str]
                     List of files that were created.

              propertyfiles_deleted:list[bytes|str]
                     List of files that were deleted.

              propertyfiles_modified:list[bytes|str]
                     List of files that were modified.

              propertyfiles_moved:list[tuple[bytes|str,bytes|str]]
                     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.

       classwatchdog.utils.dirsnapshot.EmptyDirectorySnapshot
              Bases: DirectorySnapshot

              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.

              staticpath(_:Any)->None
                     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.

              propertypaths:set
                     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.tricksmodule watchdog.tricks

       synopsis
              Utility event handlers.

       authoryesudeep@google.com (Yesudeep Mangalapilly)

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

   Classesclasswatchdog.tricks.Trick(*,patterns:list[str]|None=None,ignore_patterns:list[str]|None=None,ignore_directories:bool=False,case_sensitive:bool=False)
              Bases: PatternMatchingEventHandler

              Your tricks should subclass this class.

       classwatchdog.tricks.LoggerTrick(*,patterns:list[str]|None=None,ignore_patterns:list[str]|None=None,ignore_directories:bool=False,case_sensitive:bool=False)
              Bases: Trick

              A simple trick that does only logs events.

              on_any_event(event:FileSystemEvent)->None
                     Catch-all event handler.

                     Parametersevent (FileSystemEvent) -- The event object representing the file system event.

       classwatchdog.tricks.ShellCommandTrick(shell_command:str,*,patterns:list[str]|None=None,ignore_patterns:list[str]|None=None,ignore_directories:bool=False,wait_for_process:bool=False,drop_during_process:bool=False)
              Bases: Trick

              Executes shell commands in response to matched events.

              on_any_event(event:FileSystemEvent)->None
                     Catch-all event handler.

                     Parametersevent (FileSystemEvent) -- The event object representing the file system event.

       classwatchdog.tricks.AutoRestartTrick(command:list[str],*,patterns:list[str]|None=None,ignore_patterns:list[str]|None=None,ignore_directories:bool=False,stop_signal:Signals|int=Signals.SIGINT,kill_after:int=10,debounce_interval_seconds:int=0,restart_on_command_exit:bool=True)
              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:FileSystemEvent)->None
                     Catch-all event handler.

                     Parametersevent (FileSystemEvent) -- The event object representing the file system event.

Author

       Yesudeep Mangalapilly, Mickaël Schoentgen, and contributors

Contributing

       Welcome hacker! So you have got something you would like to see in watchdog?  Whee.  This  document  will
       help you get started.

   ImportantURLswatchdog  uses  git  to  track code history and hosts its coderepository at github. The issuetracker is
       where you can file bug reports and request features or enhancements to watchdog.

   Beforeyoustart
       Ensure your system has the following programs and libraries installed before beginning to hack:

       1. Python

       2. git

       3. XCode (on macOS)

   SettinguptheWorkEnvironment
       Steps to setting up a clean environment:

       1. Fork the coderepository into your github account.

       2. Clone fork and create virtual environment:

          $ git clone https://github.com/gorakhargosh/watchdog.git
          $ cd watchdog
          $ python -m venv venv

       3. Linux

          $ . venv/bin/activate
          (venv)$ python -m pip instal -e '.'

       4. Windows

          > venv\Scripts\activate
          (venv)> python -m pip instal -e '.'

       That's it with the setup. Now you're ready to hack on watchdog.

       Happy hacking!

       Found a bug in or want a feature added to watchdog?  You can fork the official coderepository or file an
       issue ticket at the issuetracker. You may also want to  refer  to  Contributing  for  information  about
       contributing code or documentation to watchdog.

       • IndexModuleIndexSearchPage

Directory Monitoring Made Easy With

       • A cross-platform API.

       • A shell tool to run commands in response to directory changes.

       Get started quickly with a simple example in Quickstart.

Easy Installation

       You can use pip to install watchdog quickly and easily:

          $ python -m pip install -U watchdog

       Need more help with installing? See Installation.

Installation

watchdog requires 3.9+ to work. See a list of Dependencies.

   InstallingfromPyPIusingpip
          $ python -m pip install -U watchdog

          # or to install the watchmedo utility:
          $ python -m pip install -U 'watchdog[watchmedo]'

   Installingfromsourcetarballs
          $ wget -c https://pypi.python.org/packages/source/w/watchdog/watchdog-5.0.4.tar.gz
          $ tar zxvf watchdog-5.0.4.tar.gz
          $ cd watchdog-5.0.4
          $ python -m pip install -e .

          # or to install the watchmedo utility:
          $ python -m pip install -e '.[watchmedo]'

   Installingfromthecoderepository
          $ git clone --recursive git://github.com/gorakhargosh/watchdog.git
          $ cd watchdog
          $ python -m pip install -e .

          # or to install the watchmedo utility:
          $ python -m pip install -e '.[watchmedo]'

   Dependencieswatchdog  depends on many libraries to do its job. The following is a list of dependencies you need based
       on the operating system you are using.
                          ┌─────────────────────┬─────────┬───────────┬──────────────┬─────┐
                          │ Operating    system │ Windows │ Linux 2.6 │ macOS Darwin │ BSD │
                          │ Dependency (row)    │         │           │              │     │
                          ├─────────────────────┼─────────┼───────────┼──────────────┼─────┤
                          │ XCode               │         │           │ Yes          │     │
                          └─────────────────────┴─────────┴───────────┴──────────────┴─────┘

       The  following  is  a  list  of  dependencies  you  need  based on the operating system you are using the
       watchmedo utility.
                          ┌─────────────────────┬─────────┬───────────┬──────────────┬─────┐
                          │ Operating    system │ Windows │ Linux 2.6 │ macOS Darwin │ BSD │
                          │ Dependency (row)    │         │           │              │     │
                          ├─────────────────────┼─────────┼───────────┼──────────────┼─────┤
                          │ PyYAML              │ Yes     │ Yes       │ Yes          │ Yes │
                          └─────────────────────┴─────────┴───────────┴──────────────┴─────┘

   SupportedPlatforms(andCaveats)watchdog  uses  native  APIs as much as possible falling back to polling the disk periodically to compare
       directory snapshots only when it cannot use an API natively-provided by the underlying operating  system.
       The following operating systems are currently supported:

       WARNING:
          Differences between behaviors of these native API are noted below.

       Linux2.6+
              Linux  kernel  version  2.6  and  later  come  with an API called inotify that programs can use to
              monitor file system events.

              NOTE:
                 On most systems the maximum number of watches that can be created per user is limited to  8192.
                 watchdog  needs  one  per directory to monitor. To change this limit, edit /etc/sysctl.conf and
                 add:

                     fs.inotify.max_user_watches=16384

       macOS  The Darwin kernel/OS X API maintains two ways to monitor directories for file system events:

              • kqueueFSEventswatchdog can use whichever one is available, preferring FSEvents over  kqueue(2).  kqueue(2)  uses
              open  file  descriptors  for  monitoring  and  the  current  implementation uses macOSFileSystemMonitoringPerformanceGuidelines to open these file descriptors  only  to  monitor  events,  thus
              allowing OS X to unmount volumes that are being watched without locking them.

              NOTE:
                 More  information about how watchdog uses kqueue(2) is noted in BSDUnixvariants. Much of this
                 information applies to macOS as well.

       BSDvariantscomewithkqueuewhichprogramscanusetomonitor
              changes to open file descriptors. Because of the way kqueue(2) works, watchdog needs to open these
              files and directories in read-only non-blocking mode and keep books about them.

              watchdog will automatically open file descriptors for all new files/directories created and  close
              those for which are deleted.

              NOTE:
                 The  maximum  number  of  open  file  descriptor per process limit on your operating system can
                 hinder watchdog's ability to monitor files.

                 You should ensure this limit is set to at least 1024 (or a value suitable to your  usage).  The
                 following command appended to your ~/.profile configuration file does this for you:

                     ulimit -n 1024

       WindowsVistaandlater
              The Windows API provides the ReadDirectoryChangesW. watchdog currently contains implementation for
              a  synchronous approach requiring additional API functionality only available in Windows Vista and
              later.

              NOTE:
                 Since renaming is not the same operation as movement on Windows, watchdog tries hard to convert
                 renames to movement events.  Also,  because  the  ReadDirectoryChangesW  API  function  returns
                 rename/movement events for directories even before the underlying I/O is complete, watchdog may
                 not  be  able  to  completely  scan the moved directory in order to successfully queue movement
                 events for files and directories within it.

              NOTE:
                 Since the Windows API does not provide information about whether an  object  is  a  file  or  a
                 directory, delete events for directories may be reported as a file deleted event.

       OSIndependentPollingwatchdog  also  includes  a  fallback-implementation that polls watched directories for changes by
              periodically comparing snapshots of the directory tree.

Name

       watchdog - watchdog Documentation

       Python API library and shell utilities to monitor file system events.

       Works on 3.9+.

Quickstart

       Below we present a simple example that monitors the current directory recursively (which means,  it  will
       traverse any sub-directories) to detect changes. Here is what we will do with the API:

       1. Create an instance of the watchdog.observers.Observer thread class.

       2. Implement a subclass of watchdog.events.FileSystemEventHandler.

       3. Schedule monitoring a few paths with the observer instance attaching the event handler.

       4. Start the observer thread and wait for it generate events without blocking our main thread.

       By  default,  an  watchdog.observers.Observer  instance  will  not  monitor  sub-directories.  By passing
       recursive=True in the call to watchdog.observers.Observer.schedule() monitoring entire directory trees is
       ensured.

   ASimpleExample
       The following example program will monitor the current directory recursively for file system changes  and
       simply print them to the console:

          import time

          from watchdog.events import FileSystemEvent, FileSystemEventHandler
          from watchdog.observers import Observer

          class MyEventHandler(FileSystemEventHandler):
              def on_any_event(self, event: FileSystemEvent) -> None:
                  print(event)

          event_handler = MyEventHandler()
          observer = Observer()
          observer.schedule(event_handler, ".", recursive=True)
          observer.start()
          try:
              while True:
                  time.sleep(1)
          finally:
              observer.stop()
              observer.join()

       To stop the program, press Control-C.

   Typing
       If  you  are  using  type  annotations  it  is  important to note that watchdog.observers.Observer is not
       actually a class; it is a variable that hold the "best" observer class available on your platform.

       In order to correctly type  your  own  code  your  should  use  watchdog.observers.api.BaseObserver.  For
       example:

          from watchdog.observers import Observer
          from watchdog.observers.api import BaseObserver

          def my_func(obs: BaseObserver) -> None:
              # Do something with obs
              pass

          observer: BaseObserver = Observer()
          my_func(observer)

See Also