File monitoring in Python has two main libraries, one is pyinotify (Https://github.com/seb-m/pyinotify/wiki) and the other is watchdog (http://pythonhosted.org/ watchdog/). Pyinotify relies on the inotify of the Linux platform, which encapsulates events from different platforms. Because I mainly used in the Windows platform, so the following emphasis on watchdog (recommended that you read watchdog implementation of the source code, in favor of a deep understanding of the principles).
Watchdog uses different methods for file detection on different platforms. The following comments were found in the init. PY:
|Inotify| 2.6.13+ ``inotify(7)`` based observer|FSEvents| Mac OS X FSEvents based observer|Kqueue| Mac OS X and BSD with kqueue(2) ``kqueue(2)`` based observer|WinApi|(ReadDirectoryChangesW) MS Windows Windows API-based observer|Polling| Any fallback implementation
Give the sample code as follows:
From Watchdog.observersImport ObserverFrom Watchdog.eventsImport *Import timeClassFileeventhandler(FileSystemEventHandler):Def__init__(self): filesystemeventhandler.__init__ (self)DefOn_moved(Self, event):If Event.is_directory:print ("Directory moved from {0} to {1}". Format (Event.src_path,event.dest_path))Else:print ("File moved from {0} to {1}". Format (Event.src_path,event.dest_path))Defon_created(Self, event):If Event.is_directory:print ("Directory created:{0}". Format (Event.src_path))Else:print ("File Created:{0}". Format (Event.src_path))Defon_deleted(Self, event):If Event.is_directory:print ("Directory deleted:{0}". Format (Event.src_path))Else:print ("File Deleted:{0}". Format (Event.src_path))def on_modified if event.is_directory:print (" directory modified:{0} ". Format (Event.src_path)) else:print (" file modified:{0} ". Format (Event.src_path)) if __name__ = " __MAIN__ ": Observer = Observer () Event_handler = Fileeventhandler () observer.schedule (event_handler,< Span class= "hljs-string" > "D:/DCM", true) Observer.start () Try: while true:time.sleep (1) Span class= "Hljs-keyword" >except KeyboardInterrupt:observer.stop () observer.join ()
Watchdog mainly uses the Observer model (nonsense, from the variable name can be seen). There are three main roles: Observer,event_handler, the folder being monitored. The three are originally independent, mainly through the Observer.schedule function will be strung together, meaning observer constantly detect the call platform relies on the code to detect changes in the Monitoring folder, when the change is found, notify Event_handler processing. Finally, it is recommended that readers have time to read the source code of watchdog, write it easy to understand and the structure is very good.
File change monitoring in Python-watchdog