There are two kinds of libraries for Python monitoring files: pyinotify and watchdog. Pyinotify relies on the inotify of the Linux platform, which encapsulates events from different platforms. In other words, watchdog cross-platform.
Let's look at a little demo
fromWatchdog.observersImportObserver fromWatchdog.eventsImport *ImportTimeclassFileeventhandler (FileSystemEventHandler):def __init__( Self): FileSystemEventHandler.__init__( Self)defOn_moved ( Self, event):ifEvent.is_directory:Print(the directory moved from{0} to{1}".format(Event.src_path,event.dest_path))Else:Print(the file moved from{0} to{1}".format(Event.src_path,event.dest_path))defOn_created ( Self, event):ifEvent.is_directory:Print("Directory created:{0}".format(Event.src_path))Else:Print("file created:{0}".format(Event.src_path))defOn_deleted ( Self, event):ifEvent.is_directory:Print("Directory deleted:{0}".format(Event.src_path))Else:Print("File deleted:{0}".format(Event.src_path))defOn_modified ( Self, event):ifEvent.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,"D:/DCM",True) Observer.start ()Try: while True: Time.sleep (1)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.
Watchdog official documents
Resources
Python monitor file change: watchdog