python腳本實現linux和windows下對文件夾的文件監視

主要是兩個模塊可以實現:watchdog 和 pyinotify 

pyinotify 在 linux下不需要 pip 安裝,直接就可以使用,且只能在linux中使用。

watchdog 在 linux 和 windows 下 都可以使用

 

linux 中使用pyinotify案例:

#!/usr/bin/python3
import os
import pyinotify


class MyEvent(pyinotify.ProcessEvent):
	def process_IN_CREATE(self, event):
		print("/test 目錄下有文件創建")
		os.system("python3 /hello.py")
        print("地址:{},文件名:{}".format(event.path, event.name))


def main():
	# 創建一個監控實例
	wm = pyinotify.WatchManager()
	# 添加監控的對象(路徑),rec是recursive 遞歸監視的意思
	wm.add_watch("/test", pyinotify.ALL_EVENTS, rec=True)
	# 實例化句柄
	ev = MyEvent()
	# 綁定監控對象和觸發事件
	notifier = pyinotify.Notifier(wm, ev)
	# 啓動監控(永久循環)
	notifier.loop()


if __name__ == "__main__":
	main()

這裏只監測 目錄下的文件創建,當 /test 目錄下有文件創建時,則會調用 process_IN_CREATE() 方法。

監控的條件

IN_ACCESS 文件訪問

IN_MODIFY 文件被寫入

IN_ATTRIB,文件屬性被修改,如chmod、chown、touch 等

IN_CLOSE_WRITE,可寫文件被close

IN_CLOSE_NOWRITE,不可寫文件被close

IN_OPEN,文件被open

IN_MOVED_FROM,文件被移走,如mv

IN_MOVED_TO,文件被移來,如mv、cp

IN_CREATE,創建新文件

IN_DELETE,文件被刪除,如rm

IN_DELETE_SELF,自刪除,即一個可執行文件在執行時刪除自己

IN_MOVE_SELF,自移動,即一個可執行文件在執行時移動自己

IN_UNMOUNT,宿主文件系統被umount

IN_CLOSE,文件被關閉,等同於(IN_CLOSE_WRITE | IN_CLOSE_NOWRITE)

IN_MOVE,文件被移動,等同於(IN_MOVED_FROM | IN_MOVED_TO)

參考:https://cloud.tencent.com/developer/news/219933

 

windows 下 使用watchdog 監測案例:

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


class MyEventHandler(FileSystemEventHandler):
    # def __init__(self):
    #     FileSystemEventHandler.__init__(self)

    def on_deleted(self, event):
        if event.is_directory:
            print("目錄刪除:{}".format(event.src_path))
        else:
            print("文件刪除:{}".format(event.src_path))

    def on_created(self, event):
        os.system("python D:/test/test.py hello_watchdog")
        if event.is_directory:
            print("目錄創建:{}".format(event.src_path))
        else:
            print("文件創建:{}".format(event.src_path))


if __name__ == '__main__':
    observer = Observer()
    event_handler = FileEventHandler()
    # 具體對象,監視路徑,遞歸監視
    observer.schedule(event_handler, "D:/test", True)
    observer.start()

    # 官方寫法,主要在於join方法
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()

 自定義類 MyEventHandler 繼承 FileSystemEventHandler 重寫他的 on_deleted() , on_created() 方法。FileSystemEventHandler 下面還有其他的監測方法

要監測對應的事件,重寫對應的方法即可

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章