如何监控文件的打开和关闭?

tur*_*Dev 3 linux monitoring python files

我正在写一个人工智能私人助理。该软件的一部分是监视器守护程序。一个监视用户活动窗口的小进程。我正在使用 python(使用 libwnck 和 psutils 来获取有关活动窗口的信息)。我想让我的监视器做的一件事是跟踪听众经常听的音乐。

无论如何我可以“监视”文件的打开和关闭?psutils.Process 有一个返回打开文件列表的函数,但我需要一些方法来通知它检查它。目前它只在窗口切换、窗口打开或关闭时检查进程数据。

zje*_*zje 5

您可以使用inotify子系统监控文件的打开/关闭。 pyinotify是该子系统的一个接口。

请注意,如果您有很多事件要进行 inotify,有些可以删除,但它适用于大多数情况(尤其是用户交互将驱动文件打开/关闭的情况)。

pyinotify 可通过 easy_install/pip 和https://github.com/seb-m/pyinotify/wiki 获得

MWE(基于http://www.saltycrane.com/blog/2010/04/monitoring-filesystem-python-and-pyinotify/):

#!/usr/bin/env python
import pyinotify

class MyEventHandler(pyinotify.ProcessEvent):
    def process_IN_CLOSE_NOWRITE(self, event):
        print "File closed:", event.pathname

    def process_IN_OPEN(self, event):
        print "File opened::", event.pathname

def main():
    # Watch manager (stores watches, you can add multiple dirs)
    wm = pyinotify.WatchManager()
    # User's music is in /tmp/music, watch recursively
    wm.add_watch('/tmp/music', pyinotify.ALL_EVENTS, rec=True)

    # Previously defined event handler class
    eh = MyEventHandler()

    # Register the event handler with the notifier and listen for events
    notifier = pyinotify.Notifier(wm, eh)
    notifier.loop()

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

这是相当低级的信息 - 您可能会惊讶于您的程序使用这些低级打开/关闭事件的频率。您始终可以过滤和合并事件(例如,假设在特定时间段内为同一文件接收到的事件对应于相同的访问)。