def watchFileChange_2(path_to_watch, func_handle_change=None): import win32file import win32event import win32con #path_to_watch = os.path.abspath (".") # # FindFirstChangeNotification sets up a handle for watching # file changes. The first parameter is the path to be # watched; the second is a boolean indicating whether the # directories underneath the one specified are to be watched; # the third is a list of flags as to what kind of changes to # watch for. We're just looking at file additions / deletions. # change_handle = win32file.FindFirstChangeNotification( path_to_watch, 0, win32con.FILE_NOTIFY_CHANGE_FILE_NAME) # # Loop forever, listing any file changes. The WaitFor... will # time out every half a second allowing for keyboard interrupts # to terminate the loop. # try: old_path_contents = dict([(f, None) for f in os.listdir(path_to_watch)]) while 1: result = win32event.WaitForSingleObject(change_handle, 500) # # If the WaitFor... returned because of a notification (as # opposed to timing out or some error) then look for the # changes in the directory contents. # if result == win32con.WAIT_OBJECT_0: new_path_contents = dict([(f, None) for f in os.listdir(path_to_watch)]) added = [ f for f in new_path_contents if not f in old_path_contents ] deleted = [ f for f in old_path_contents if not f in new_path_contents ] if added: changes = [] for i in added: changes.append((3, os.path.join(path_to_watch, i))) print("Added: ", ", ".join(added)) t = threading.Thread(target=func_handle_change, args=(changes, )) t.start() if deleted: print("Deleted: ", ", ".join(deleted)) old_path_contents = new_path_contents win32file.FindNextChangeNotification(change_handle) finally: win32file.FindCloseChangeNotification(change_handle)
def run(self): self.__is_running = True self.__change_handles = None self.__dirs = {} try: while self.__is_running: self.__refresh_requests() if self.__change_handles is None: for monitor in self.__dirs.values(): # Newly added if monitor.get_change_handle() is None: monitor.set_change_handle( win32file.FindFirstChangeNotification( monitor.get_dir(), 0, win32con.FILE_NOTIFY_CHANGE_FILE_NAME)) # Refresh change handlers cache print "Refreshing change-handles cache" self.__change_handles = {} for monitor in [ monitor for monitor in self.__dirs.values() if monitor.get_change_handle() ]: self.__change_handles[ monitor.get_change_handle()] = monitor print self.__change_handles #old_path_contents = os.listdir (self.path_to_watch) if len(self.__change_handles) > 0: result = win32event.WaitForMultipleObjects( self.__change_handles.keys(), False, 500) else: result = win32con.WAIT_FAILED if (result >= win32con.WAIT_OBJECT_0) and ( result <= win32con.WAIT_OBJECT_0 + len(self.__change_handles) - 1): changed_handle = self.__change_handles.keys()[result] #print changed_handle monitor = self.__change_handles[changed_handle] #print monitor.get_dir() #print monitor.get_handlers() added, deleted, modified = monitor.reload_file_changes() if len(added) > 0 or len(deleted) > 0 or len(modified) > 0: logging.info(monitor.get_handlers()) self.__serve_handlers(monitor, added, deleted, modified) win32file.FindNextChangeNotification(changed_handle) finally: for monitor in self.__dirs.values(): if monitor.get_change_handle(): win32file.FindCloseChangeNotification( monitor.get_change_handle()) monitor.set_change_handle(None) self.__success = True logging.info("Directory watcher finished")
def run(self): # # FindFirstChangeNotification sets up a handle for watching # file changes. The first parameter is the path to be # watched; the second is a boolean indicating whether the # directories underneath the one specified are to be watched; # the third is a list of flags as to what kind of changes to # watch for. We're just looking at file additions / deletions. # change_handle = win32file.FindFirstChangeNotification( self.latus_folder, 0, win32con.FILE_NOTIFY_CHANGE_FILE_NAME) # This order is important. If multiple events are triggered, only the lowest index is # indicated. So, the exit event must be the lowest index or else we could miss # the exit event if it happens as the same time as a file system change. wait_objects = [change_handle] if self.exit_event_handle is not None: wait_objects.insert(0, self.exit_event_handle) # prepend # # Loop forever, listing any file changes. The WaitFor... will # time out every half a second allowing for keyboard interrupts # to terminate the loop. # exit_flag = False try: old_path_contents = self.local_folder_contents() while not exit_flag: result = win32event.WaitForMultipleObjects( wait_objects, 0, 10 * 1000) print('WaitForMultipleObjects', result) # # If the WaitFor... returned because of a notification (as # opposed to timing out or some error) then look for the # changes in the directory contents. # if result == win32con.WAIT_OBJECT_0: exit_flag = True elif result == win32con.WAIT_OBJECT_0 + 1: new_path_contents = self.local_folder_contents() added = [ f for f in new_path_contents if not f in old_path_contents ] deleted = [ f for f in old_path_contents if not f in new_path_contents ] self.sync(added, deleted) old_path_contents = new_path_contents win32file.FindNextChangeNotification(change_handle) finally: win32file.FindCloseChangeNotification(change_handle)
def SvcDoRun(self): self.ReportServiceStatus(win32service.SERVICE_START_PENDING) log('starting') self.ReportServiceStatus(win32service.SERVICE_RUNNING) self.modification_handle = get_config_modification_handle( self._base_path) self.configuration_mtime = os.stat( os.path.join(self._base_path, self._config_filename)).st_mtime keep_running = True do_start = True while keep_running: # do the actual start if do_start: self.start() log('Started. Waiting for stop') index = win32event.WaitForMultipleObjects( [self.stop_event, self.modification_handle], False, win32event.INFINITE) if index == 0: # The stop event has been signaled. Stop execution. keep_running = False else: # re-initialise handle win32file.FindNextChangeNotification(self.modification_handle) new_mtime = os.stat( os.path.join(self._base_path, self._config_filename)).st_mtime if new_mtime != self.configuration_mtime: self.configuration_mtime = new_mtime do_start = True log('Restarting child processes as the configuration has changed' ) self.stop() self.config = read_config(self._base_path, self._config_filename) else: do_start = False win32file.FindCloseChangeNotification(self.modification_handle)
def watch(): """ Windows only """ import win32file, win32event, win32con watchPath = os.path.abspath(".") change_handle = win32file.FindFirstChangeNotification( watchPath, 0, win32con.FILE_NOTIFY_CHANGE_LAST_WRITE) try: while 1: result = win32event.WaitForSingleObject(change_handle, 500) if (result == win32con.WAIT_OBJECT_0): update() win32file.FindNextChangeNotification(change_handle) finally: win32file.FindCloseChangeNotification(change_handle)
def event_loop(self): logger.debug("Starting event notification loop") change_handle = win32file.FindFirstChangeNotification( str(self.path), 0, win32con.FILE_NOTIFY_CHANGE_LAST_WRITE) try: while self.stop_thread == False: result = win32event.WaitForSingleObject(change_handle, 500) # # If the WaitFor... returned because of a notification (as # opposed to timing out or some error) then look for the # changes in the directory contents. # if result == win32con.WAIT_OBJECT_0: self.on_event() win32file.FindNextChangeNotification(change_handle) except KeyboardInterrupt: self.stop_thread = True finally: win32file.FindCloseChangeNotification(change_handle) logger.debug("stopping notification loop")
def monitoring_win32(self): """Watch trace directory for new files (Windows only)""" while not self.monitoring_win32_cancelled: from os.path import exists from time import sleep if not exists(self.directory): sleep(1) else: # watchdog: "Failed to import read_directory_changes. Fall back to polling" # http://code.activestate.com/recipes/156178-watching-a-directory-under-win32/ import win32file, win32event, win32con change_handle = win32file.FindFirstChangeNotification( directory, 0, win32con.FILE_NOTIFY_CHANGE_FILE_NAME) try: while self.monitoring_win32_cancelled: result = win32event.WaitForSingleObject( change_handle, 500) if result == win32con.WAIT_OBJECT_0: self.handler(*self.args, **self.kwargs) win32file.FindNextChangeNotification(change_handle) finally: win32file.FindCloseChangeNotification(change_handle)
def watchFile(): #setup the notifciation watchNotification = win32file.FindFirstChangeNotification(messagePath,0,win32con.FILE_NOTIFY_CHANGE_SIZE) try: while 1: #print "Watching" result = win32event.WaitForSingleObject(watchNotification, 500) #If there was a change if result == win32con.WAIT_OBJECT_0: #Read the message file readMessages(messageFile) #Start watching again for next notification win32file.FindNextChangeNotification (watchNotification) finally: #close it all down print "Closing the notification watch" win32file.FindCloseChangeNotification (watchNotification)
f for f in new_path_contents if not f in old_path_contents ] #deleted = [f for f in old_path_contents if not f in new_path_contents] #if added: print "Added: ", ", ".join (added) #if deleted: print "Deleted: ", ", ".join (deleted) # My open for item in added: #print item match_hdr = re.search(r'\.hdr$', item, re.M) if match_hdr: #print "HDR FOUND" fullfilename = os.path.join(path, item) hdr_file = open(fullfilename, 'r') #print '__________________________________\n' print "Job received on server @:", datetime.datetime.now( ), '\n' for line in hdr_file: if 'ENTITY_MODE' in line: print line, if 'ENTITY_NAME' in line: print line, if 'JOB_NAME' in line: print line, if 'PRINTER_NAME' in line: print line, if 'JOB_TOTAL_PAGES' in line: print line, if 'JOB_NB_COPY' in line: print line, print '_______________________________________\n' hdr_file.close() old_path_contents = new_path_contents win32file.FindNextChangeNotification(change_handle) finally: win32file.FindCloseChangeNotification(change_handle)
def stop(self): win32file.FindCloseChangeNotification(self.handle)
def __wait_for_client_to_open_from_lockfile(self, check_interval=3, timeout=float('inf')): import os import win32file import win32event import win32con retried = 0 path_to_watch = os.path.join(self.install_directory) if "lockfile" in os.listdir(path_to_watch): return retried # FindFirstChangeNotification sets up a handle for watching # file changes. The first parameter is the path to be # watched; the second is a boolean indicating whether the # directories underneath the one specified are to be watched; # the third is a list of flags as to what kind of changes to # watch for. We're just looking at file additions / deletions. change_handle = win32file.FindFirstChangeNotification( path_to_watch, 0, win32con.FILE_NOTIFY_CHANGE_FILE_NAME) # Loop forever, listing any file changes. The WaitFor... will # time out every N/1000 seconds allowing for keyboard interrupts # to terminate the loop. try: old_path_contents = dict([(f, None) for f in os.listdir(path_to_watch)]) while True: result = win32event.WaitForSingleObject( change_handle, check_interval * 1000) # If the WaitFor... returned because of a notification (as # opposed to timing out or some error) then look for the # changes in the directory contents. if result == win32con.WAIT_OBJECT_0: new_path_contents = dict([ (f, None) for f in os.listdir(path_to_watch) ]) added = [ f for f in new_path_contents if not f in old_path_contents ] #deleted = [f for f in old_path_contents if not f in new_path_contents] if "lockfile" in added: time.sleep( 1 ) # Wait another second for the lockfile to be written to break old_path_contents = new_path_contents win32file.FindNextChangeNotification(change_handle) retried += check_interval self.__check_systray_alive() if retried > timeout: raise TimeoutError( f"Timed out waiting for LCU to open. Waited for {retried} seconds." ) finally: win32file.FindCloseChangeNotification(change_handle) return retried