python实现监控文件状态功能

8/7/2023 python
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pyinotify


def do_sth():
    print('此处执行任何你要做的操作!')


class MyEventHandler(pyinotify.ProcessEvent):
    # 当文件被修改时调用函数
    def process_IN_CREATE(self, event):
        print('文件被创建')
        print('path', event.path)
        print('pathname', event.pathname)
        print('name', event.name)

    def process_IN_DELETE(self, event):
        print('文件被删除')

    def process_IN_MODIFY(self, event):
        do_sth()


def main():
    try:
        # 输出前面的log
        # watch manager
        wm = pyinotify.WatchManager()
        # 设置要监控的文件,监控修改事件
        wm.add_watch('/data/test', pyinotify.IN_MODIFY, rec=True)
        eh = MyEventHandler()

        # notifier
        notifier = pyinotify.Notifier(wm, eh)
        notifier.loop()
    except Exception as e:
        print('捕捉到异常', e)
    finally:
        notifier.stop()


if __name__ == '__main__':
    main()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
Last Updated: 6/1/2024, 6:36:28 AM