You can monitor the opening/closing of files using the
pyinotify is one interface to this subsystem.
Note that if you have a lot of events going to inotify, some can be dropped, but it works for most cases (especially your case in which user interaction will drive the opening/closing of files).
pyinotify is available via easy_install/pip and at https://github.com/seb-m/pyinotify/wiki
MWE (based on http://www.saltycrane.com/blog/2010/04/monitoring-filesystem-python-and-pyinotify/):
def process_IN_CLOSE_NOWRITE(self, event):
print "File closed:", event.pathname
def process_IN_OPEN(self, event):
print "File opened::", event.pathname
# 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)
if __name__ == '__main__':
This is quite low-level information - you might be surprised how often your program uses these low-level open/close events. You can always filter and coalesce events (for example, assume events received for the same file in a certain time period correspond to the same access).