import os, sys import winerror import win32file import win32con if __name__ == '__main__': path_to_watch = sys.argv[1] hDir = win32file.CreateFile ( path_to_watch, 1, # FILE_LIST_DIRECTORY win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS, None ) print "=> Watching", path_to_watch watching = set () handles = [] try: while 1: results = win32file.ReadDirectoryChangesW ( hDir, 1024, True, win32con.FILE_NOTIFY_CHANGE_FILE_NAME, None, None ) for action, filename in results: filename = os.path.join (path_to_watch, filename) if action == 1 and filename not in watching: try: handle = win32file.CreateFile ( filename, 0, win32file.FILE_SHARE_DELETE, None, win32file.OPEN_EXISTING, 0, 0 ) handles.append (handle) except win32file.error, (errno, module, message): if errno == winerror.ERROR_SHARING_VIOLATION: print ".. Can't hold", repr (filename) else: print ".. Problem with %r: %s" % (filename, message) else: watching.add (filename) print ".. Holding", repr (filename) handle.Close () handles.remove (handle) watching.discard (filename) print ".. Released", repr (filename) finally: for handle in handles: handle.Close () hDir.Close ()