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 下面还有其他的监测方法

要监测对应的事件,重写对应的方法即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值