All pastes #518382 Raw Edit

Something

public text v1 · immutable
#518382 ·published 2007-05-29 09:09 UTC
rendered paste body
# newshiz3 watcher 0.1, creates picklefile in /tmp max every 1 minutes
# usage: ./simple.py '/path-to-watch'

import os
from datetime import datetime, timedelta
import pickle
from pyinotify import SimpleINotify, EventsCodes, ProcessEvent

createdlist = []
lastpickled = None

class PCreate(ProcessEvent):
    def process_IN_CREATE(self, event_k):
        """
        process 'IN_CREATE_*' events by checking to see if file is a directory
        """
        if event_k.name:
            createdname = os.path.join(event_k.path, event_k.name)
            f = "%s" % createdname
            if event_k.isdir:
                print "%s: created (directory), adding to watchlist." % f
                ino.add_watch(event_k.path, mask, PCreate(), rec=True)
            else:
                # heart math operations on datetime objects
                timeadded = datetime.now()
                try:
                    if lastpickled:
                        pass
                except:
                    lastpickled = timeadded
                print "%s: created file, adding to createdlist with timestamp %s (lastpickled %s)" % (f, timeadded, lastpickled)
                createdlist.append([createdname, timeadded])
                if timeadded - lastpickled > timedelta(minutes=1):
                    print "pickling createdlist to /tmp/newshiz"
                    picklefile = open("/tmp/newshiz",'w')
                    pickle.dump(createdlist, picklefile)
                    picklefile.close()
                    
        else:
            # in example but have never seen this get called
            print "move along, nothing to see here."
            f = "%s" % event_k.path

if __name__ == '__main__':
    #
    import sys

    path = '/home/tom/code' # default watched path
    if sys.argv[1:]:
        path = sys.argv[1]

    # only interested in create/destroy
    mask = EventsCodes.IN_MODIFY | EventsCodes.IN_DELETE | \
           EventsCodes.IN_CREATE

    # class instance and init
    ino = SimpleINotify()

    print "this is newshiz3, derived from simple.py"
    print 'start monitoring %s with mask %d' % (path, mask)
    added_flag = False

    while True:
        
        try:
            if not added_flag:
                print "adding root: %s"%path
                ino.add_watch(path, mask, PCreate(),rec=True)              
                added_flag = True
            ino.process_events()
            if ino.event_check():
                ino.read_events()
        except KeyboardInterrupt:
            # ...until c^c signal
            print 'stop monitoring...'
            # close inotify's instance
            ino.close()
            break
        except Exception, err:
            # otherwise keep on watching
            print err