Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธี Monitor ไฟล์ Python เพื่อตรวจจับการเปลี่ยนแปลง

การ monitor ไฟล์ข้ามแพลตฟอร์มยาก แต่ Python มีไลบรารี watchdog ที่นิยมใช้ ติดตั้งด้วย:

$ pip install watchdog

ตัวอย่าง: ติดตามไฟล์ my_file.txt

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()

เมื่อรันโปรแกรมและแก้ไขไฟล์ในไดเรกทอรีปัจจุบัน ฟังก์ชัน on_modified จะถูกเรียก กด Ctrl+C เพื่อหยุด