watchdog python
时间: 2023-10-28 10:57:19 浏览: 116
python中文件变化监控示例(watchdog)
Watchdog is a Python library that allows you to monitor file system events, such as files being created, deleted, or modified. It provides a simple and efficient way to automate tasks based on these events. Here's an example of how you can use Watchdog in Python:
```python
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
# Create a class that inherits from FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
print(f'File {event.src_path} was modified')
# Create an observer and attach the handler
observer = Observer()
observer.schedule(MyHandler(), path='.')
# Start the observer in a separate thread
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
```
In this example, we create a class `MyHandler` that inherits from `FileSystemEventHandler`. We override the `on_modified` method to print a message whenever a file is modified. We then create an `Observer`, attach our handler to it, and start the observer in a separate thread. Finally, we run the observer until it is stopped by pressing Ctrl+C.
This is just a basic example, and Watchdog offers many more features and event types that you can use. You can find more information and examples in the official documentation: https://python-watchdog.readthedocs.io/
阅读全文