wait until change

Dave Benjamin ramen at lackingtalent.com
Fri Oct 17 15:47:48 EDT 2003


In article <3F90424E.A5301708 at engcorp.com>, Peter Hansen wrote:
> 
> Also, note that there are non-cross-platform solutions that basically
> notify your program "as soon as" (possibly without any latency guarantees)
> a change has happened.  They are harder to use and quite likely unnecessary
> in your case, and the time.sleep() approach Tim points out is simpler
> and therefore the best thing to start with.

Here's one that uses PythonWin and WMI. I wrote this awhile ago because I
was experimenting with writing a templating system that would process input
files "on the fly" whenever they changed. It seems to drive my CPU usage up,
though - not sure why, because I'm pretty sure that events.NextEvent()
blocks until an event comes. Anyway, I don't know if this is useful to
anyone, but here it is... (apologies for the wide margins):

import time, win32com; time.sleep(1)
from win32com.client import GetObject

interval  = 1
filenames = [r'c:\test.txt', r'c:\output.txt']

class FileChangeEvent:
    def __init__(self, filename, new_size, old_size):
        self.filename = filename
        self.new_size = new_size
        self.old_size = old_size

def on_change(event):
    print event.__dict__

wmi      = GetObject(r'winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2')
filespec = ' OR '.join(["TargetInstance.Name='%s'" % filename.replace('\\', '\\\\') for filename in filenames])
query    = "SELECT * FROM __InstanceModificationEvent WITHIN %d WHERE TargetInstance ISA 'CIM_DataFile' AND (%s)" % (interval, filespec)
events   = wmi.ExecNotificationQuery(query)

while True:
      event = events.NextEvent()
      on_change(FileChangeEvent(str(event.TargetInstance.Name),
                                int(event.TargetInstance.FileSize),
                                int(event.PreviousInstance.FileSize)))

-- 
.:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g   l i f e   o u t   o f   t h e   c o n t a i n e r :




More information about the Python-list mailing list