This article mainly introduces the file change monitoring example (watchdog) in python. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.
There are two main libraries for file monitoring in python, one is pyinotify (https://github.com/seb-m/pyinotify/wiki) and the other is watchdog ( http://pythonhosted.org/watchdog/). pyinotify relies on the Linux platform's inotify, which encapsulates events on different platforms. Because I mainly use it on the Windows platform, I will focus on watchdog below (it is recommended that you read the watchdog implementation source code, which will help you deeply understand the principles).
watchdog uses different methods for file detection on different platforms. The following comments were found in init.py:
|Inotify| Linux 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
The sample code is given as follows:
##
from watchdog.observers import Observer from watchdog.events import * import time class FileEventHandler(FileSystemEventHandler): def __init__(self): FileSystemEventHandler.__init__(self) def on_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)) def on_created(self, event): if event.is_directory: print("directory created:{0}".format(event.src_path)) else: print("file created:{0}".format(event.src_path)) def on_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(self, event): 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,"d:/dcm",True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
The above is the detailed content of Example of file change monitoring watchdog in python. For more information, please follow other related articles on the PHP Chinese website!