Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách theo dõi thay đổi file Python?


Theo dõi thay đổi file trong mọi ngôn ngữ đều khó do vấn đề cross-platform. Trên Python, có thư viện cross-platform phổ biến tên watchdog cho phép theo dõi thay đổi. Cài đặt bằng:

$ pip install watchdog

Ví dụ

Để theo dõi file my_file.txt dùng watchdog, chương trình đơn giản:

import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        print("Got it!")

event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path='.', recursive=False)
observer.start()
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()
observer.join()

Khi chạy chương trình và sửa bất kỳ file nào trong thư mục hiện tại, hàm on_modified của class MyHandler được gọi với event. Trong class MyHandler bạn tự định nghĩa hàm xử lý event. Trong path, chỉ định file/thư mục muốn theo dõi. Để dừng, dùng Ctrl + C.