我在写人工智能的私人助理。该软件的一部分是监视器守护进程。监视用户活动窗口的小进程。我使用python(使用libwnck和psutils获取活动窗口的信息)。我想让我的班长做的一件事就是跟踪听众经常听的音乐。
我是否可以“监控”文件的打开和关闭?psutils.Process有一个返回打开文件列表的函数,但我需要某种方式通知它来检查它。目前,它只在窗口切换或打开或关闭窗口时检查处理数据。
发布于 2015-06-03 16:01:09
您可以使用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()这是相当低级别的信息--您可能会惊讶于您的程序经常使用这些低级别的打开/关闭事件。您可以始终筛选和合并事件(例如,假设在特定时间内为同一文件接收的事件对应于相同的访问)。
https://unix.stackexchange.com/questions/207304
复制相似问题