def __init__(self, path): try: self.change_handle = win32file.FindFirstChangeNotification( path, 0, FolderChanges.flags) except pywintypes.error: pass # This happens when the config folder doesn't exist self.changed = False
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 __init__(self, dirname): self.DirName = dirname self.Files = {} self.ChangeHandle = win32file.FindFirstChangeNotification( self.DirName, 0, win32con.FILE_NOTIFY_CHANGE_LAST_WRITE | win32con.FILE_NOTIFY_CHANGE_FILE_NAME)
def run(self): dirName = self.dirPath hdir = win32file.CreateFile( dirName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, win32security.SECURITY_ATTRIBUTES(), OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0) filter = FILE_NOTIFY_CHANGE_FILE_NAME | \ FILE_NOTIFY_CHANGE_DIR_NAME \ | FILE_NOTIFY_CHANGE_ATTRIBUTES | \ FILE_NOTIFY_CHANGE_LAST_WRITE | \ FILE_NOTIFY_CHANGE_SIZE win32Handle = win32file.FindFirstChangeNotification( dirName, True, filter) while UtilFunc.programIsRunning(): results = win32file.ReadDirectoryChangesW( hdir, 819600, True, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | \ FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE | \ FILE_NOTIFY_CHANGE_CREATION, # FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_LAST_ACCESS |FILE_NOTIFY_CHANGE_SECURITY None, None ) for action, file in results: path = file if path == 'Thumbs.db': continue path = os.path.join(dirName, path) path = path.replace('\\', '/') if '/.popoCloud/' in path or os.path.basename( path) == '.popoCloud': continue # print str(action) + " " + path if action == 1 or action == 5: if os.path.isdir(path): ProfileFunc.addToLibrary(path) else: ProfileFunc.addFileCache(path) elif action == 2 or action == 4: ProfileFunc.delFileCache(path) elif action == 3: if not os.path.isdir(path): ProfileFunc.delFileCache(path) ProfileFunc.addFileCache(path) win32file.FindNextChangeNotification(win32Handle)
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 __init__(self): self.change_detected = False self.filename = __file__ if self.filename.endswith("c") or self.filename.endswith("o"): self.filename = self.filename[:-1] self.handle = win32file.FindFirstChangeNotification( os.path.dirname(self.filename), False, # watch tree? win32con.FILE_NOTIFY_CHANGE_LAST_WRITE) threading.Thread.__init__(self)
def get_config_modification_handle(path=None): '''Returns a Directory change handle on the configuration directory. This handle will be used to restart the Django commands child processes in case the configuration file has changed in the directory. ''' if not path: path = dirname(abspath(__file__)) change_handle = win32file.FindFirstChangeNotification( path, 0, win32con.FILE_NOTIFY_CHANGE_LAST_WRITE) return change_handle
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 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 watch_win32(self, dir_to_watch): '''os-specific watch command''' # Loop forever, listing any file changes. The WaitFor... will # time out every half a second allowing for keyboard interrupts # to terminate the loop. files_added = [] old_path_contents = [] new_path_contents = [] cnt = 0 try: while 1: cnt += 1 #print 'Watching %s' % cnt #old_path_contents = os.listdir(dirToWatch) for item in dir_to_watch: change_handle = win32file.FindFirstChangeNotification( item, 0, win32con.FILE_NOTIFY_CHANGE_FILE_NAME) old_path_contents.append(os.listdir(item)) 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 = os.listdir(dirToWatch) # build the new list with all the files from all dirs for item in dir_to_watch: new_path_contents.append(os.listdir(item)) files_added = [ f for f in new_path_contents if not f in old_path_contents ] #files_deleted = [f for f in old_path_contents if not f in new_path_contents] if files_added: print() print(time.asctime()) print("Added:", files_added or "Nothing") return files_added #print "Deleted:", files_deleted or "Nothing" win32file.FindNextChangeNotification(change_handle) except KeyboardInterrupt: return []
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)
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 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")
for opt, arg in opts: if opt == '-p': serial_port = arg elif opt == '-d': observed_dir = arg trash_mode = False # # 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( observed_dir, 0, win32con.FILE_NOTIFY_CHANGE_FILE_NAME) connect_to_serial(serial_port) print('Connected to ' + arduino_ser.name) Thread(target=check_presence).start() # Inital print time.sleep(2) print_count() try: while True: result = win32event.WaitForSingleObject(change_handle, 500) #
def getChangeHandle(): handle = win32file.FindFirstChangeNotification( watchDir, 0, win32con.FILE_NOTIFY_CHANGE_FILE_NAME) return 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
import glob, os from solid import * #http://solidpython.readthedocs.io/en/latest/ import os, solid os.chdir("./scad.py") path_to_watch = os.path.abspath(".") file_times = {} for file in glob.glob("*.py"): file_times[file] = os.stat(file).st_mtime change_handle = win32file.FindFirstChangeNotification( path_to_watch, 0, win32con.FILE_NOTIFY_CHANGE_LAST_WRITE) try: while 1: result = win32event.WaitForSingleObject(change_handle, 500) if result == win32con.WAIT_OBJECT_0: for file in glob.glob("*.py"): statbuf = os.stat(file) if (statbuf.st_mtime - file_times[file]) > 0.1: #100 ms debounce file_times[file] = statbuf.st_mtime print file + ": has new save time:", statbuf.st_mtime cmd = 'python ' + '"' + file + '"' print(" => " + os.getcwd() + ">" + cmd) os.system(cmd) win32file.FindNextChangeNotification(change_handle)
# author Abhiroop Dabral # v 1.0 import os import re import datetime import win32file import win32event import win32con import string path = r"C:\Users\dZONE\Desktop\py" # path to watch for change_handle = win32file.FindFirstChangeNotification( path, 0, win32con.FILE_NOTIFY_CHANGE_FILE_NAME) try: old_path_contents = dict([(f, None) for f in os.listdir(path)]) while 1: result = win32event.WaitForSingleObject(change_handle, 500) if result == win32con.WAIT_OBJECT_0: new_path_contents = dict([(f, None) for f in os.listdir(path)]) 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: print "Added: ", ", ".join (added) #if deleted: print "Deleted: ", ", ".join (deleted)
def walk(path): ''' gets path, returns all the subfolder tree under the given path ''' m = [] for root, directories, filenames in os.walk(path): for filename in filenames: m.append(os.path.join(root, filename)) return m #------------------------ path = "D:\Elik\HW_Golan\Temporary Internet Files" changeHandle = win32file.FindFirstChangeNotification( path, # where to look for True, # looking for changes not only in this directory, but in sub-directories too win32con. FILE_NOTIFY_CHANGE_FILE_NAME # looking for recently added / deleted files ) print "waiting for changes on hadle: " + str(changeHandle) # navigation to link with win32com.client: ieApp = win32com.client.Dispatch("InternetExplorer.Application") #ieApp.Visible = True ieApp.Navigate('http://google.com/search?q=frc&tbm=isch') # stop_handles holds one handle for the notifications and another one for standard winapi input. the second handle waits for input from the keyboard and is used to stop the 'while true' loop by cliking on any key stop_handles = [changeHandle, win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)] # before = os.listdir(path) before = walk(path) while True: