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)
Example #2
0
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)
Example #3
0
 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 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")
Example #5
0
    def wait_for_beat_and_get_changed_folders(wait_period, changing_folders):

        returning_changed_folders = dict()

        # Make sure that the interval does not include milliseconds, yet still promoting
        # that calculations using interval can include milliseconds in their results.
        interval = round(wait_period, 0)
        this_second = current_seconds_milliseconds()
        max_seconds = float(int(this_second + interval))
        if max_seconds > 60.0:
            max_seconds = 1.0
        wait_for = round(interval - this_second % interval, 3)
        interrupter = None
        while (wait_for >= 60.0) or (0.0 <= this_second < max_seconds):
            try:
                interrupter = win32event.WaitForMultipleObjects(
                    changing_folders.win32_handles, 0, int(
                        1000.0 * wait_for)) - win32event.WAIT_OBJECT_0
            except IOError as e:
                if e.errno != errno.EINTR:
                    raise
            except KeyboardInterrupt:
                return None
            except pywintypes.error:
                pass  # This happens when the config folder doesn't exist

            this_second = current_seconds_milliseconds()
            if max_seconds > 59.0:
                max_seconds = 0.0
            wait_for = round(interval - this_second % interval, 3)

            if interrupter is not None and interrupter < len(
                    changing_folders.win32_handles):
                returning_changed_folders[changing_folders.paths[interrupter]] =\
                    changing_folders.callbacks[changing_folders.paths[interrupter]]
                win32file.FindNextChangeNotification(
                    changing_folders.win32_handles[interrupter])

        return returning_changed_folders
Example #6
0
 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)
Example #7
0
    def __Tick(self):
        if len(self.__watchedDirs) == 0: return

        changes = set()

        while 1:
            #TODO: Split wds if longer that 256 (?) - check limit for WaitForMultipleObjects
            wds = self.__watchedDirs.values()
            handles = [x.ChangeHandle for x in wds]
            result = win32event.WaitForMultipleObjects(handles, 0, 0)
            if result == win32con.STATUS_TIMEOUT: break

            win32file.FindNextChangeNotification(handles[result])
            changes.add(wds[result])

        if len(changes) > 0:
            L.debug(
                "Loader FS Watchdog discovered '%d' change(s) on filesystem" %
                len(changes))

        for wds in changes:
            wds.OnChangeInDir()
Example #8
0
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)
Example #9
0
                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)
Example #10
0
while True:
    # result = return value form waitfor... [ for infinite time until there were updates in the handle-path ]
    # result gets 0 if the return was because of a change-event. (otherwise it is an exception or some other error)
    result = win32event.WaitForMultipleObjects(
        stop_handles, 0, win32event.INFINITE
    )  # -> (handles, wait for one(0) / wait for all(1), event for one - infinte time)
    if result == win32con.WAIT_OBJECT_0:  # ( if result == 0 ) 0 is the first handle in the []
        # after = os.listdir(path)
        after = walk(path)
        added = [f for f in after if not f in before]
        if len(added) != 0:
            print "Added: ", ", ".join(added)
            for i in added:
                if i[-4:] == '.png' or i[-4:] == '.jpg' or i[
                        -4:] == '.bmp' or i[-4:] == '.ico' or i[
                            -4:] == '.gif':  # or whatever other format :)
                    win32file.CopyFile(
                        i, 'D:\\Elik\\HW_Golan\\PICS\\New folder\\' +
                        i.rsplit('\\', 1)[1], False)
                    print "copied: ", ", ".join(added)
        before = after
        win32file.FindNextChangeNotification(
            changeHandle
        )  # same as FindFirst... but with an already existing handle

    elif result == win32con.WAIT_OBJECT_0 + 1:  #( if result == 1 ) 1 is the first handle in the []
        break

win32file.FindCloseChangeNotification(changeHandle)
print '++++++++++++++++++++++++\r\nstopped'
Example #11
0
    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