Esempio n. 1
0
    def waitForFile(self, filename: str, timeout: int = 0) -> Optional[str]:
        """
        Wait for a specific filename to be created in the directory specified in initFileNotifier.
        Args:
            filename: Name of File to watch for creation of. If filename includes a path it must 
                match that specified in initFileNotifier.
            timeout: Max number of seconds to watch for the file creation. If timeout expires
                before the file is created then None will be returned
        Returns:
            The filename of the created file (same as input arg) or None if timeout expires
        """
        _filedir, _filename = os.path.split(filename)
        if _filedir in (None, ''):
            filename = os.path.join(self.watchDir, filename)
        elif _filedir != self.watchDir:
            raise StateError(
                f"FileWatcher: file path doesn't match watch directory: {_filedir}, {self.watchDir}"
            )

        fileExists = os.path.exists(filename)
        if not fileExists:
            if self.notify_thread is None:
                raise FileNotFoundError(
                    "No fileNotifier and dicom file not found %s" % (filename))
            else:
                logStr = "FileWatcher: Waiting for file {}, timeout {}s ".format(
                    filename, timeout)
                logging.log(DebugLevels.L6, logStr)
        eventLoopCount = 0
        exitWithFileEvent = False
        eventTimeStamp = 0
        startTime = time.time()
        timeToCheckForFile = time.time(
        ) + 1  # check if file exists at least every second
        while not fileExists:
            if timeout > 0 and time.time() > (startTime + timeout):
                return None
            # look for file creation event
            eventLoopCount += 1
            try:
                eventfile, ts = self.fileNotifyQ.get(block=True, timeout=1.0)
            except Empty:
                # The timeout occured on fileNotifyQ.get()
                fileExists = os.path.exists(filename)
                continue
            if eventfile is None:
                raise StateError('waitForFile: eventfile is None')
            # We may have a stale event from a previous file if multiple events
            #   are created per file or if the previous file eventloop
            #   timed out and then the event arrived later.
            if eventfile == filename:
                fileExists = True
                exitWithFileEvent = True
                eventTimeStamp = ts
                continue
            if time.time() > timeToCheckForFile:
                # periodically check if file exists, can occur if we get
                #   swamped with unrelated events
                fileExists = os.path.exists(filename)
                timeToCheckForFile = time.time() + 1
        if exitWithFileEvent is False:
            # We didn't get a file-close event because the file already existed.
            # Check the file size and sleep up to 300 ms waitig for full size
            waitIncrement = 0.1
            totalWriteWait = 0.0
            fileSize = os.path.getsize(filename)
            while fileSize < self.minFileSize and totalWriteWait < 0.3:
                time.sleep(waitIncrement)
                totalWriteWait += waitIncrement
                fileSize = os.path.getsize(filename)
        logging.log(
            DebugLevels.L6,
            "File avail: eventLoopCount %d, fileEventCaptured %s, "
            "fileName %s, eventTimeStamp %d", eventLoopCount,
            exitWithFileEvent, filename, eventTimeStamp)
        if self.demoStep is not None and self.demoStep > 0:
            self.prevEventTime = demoDelay(self.demoStep, self.prevEventTime)
        return filename
Esempio n. 2
0
    def waitForFile(self, specificFileName, timeout=0):
        fileExists = os.path.exists(specificFileName)
        if not fileExists:
            if self.observer is None:
                raise FileNotFoundError(
                    "No fileNotifier and dicom file not found %s" %
                    (specificFileName))
            else:
                logStr = "FileWatcher: Waiting for file {}, timeout {}s ".format(
                    specificFileName, timeout)
                logging.log(DebugLevels.L6, logStr)
        eventLoopCount = 0
        exitWithFileEvent = False
        eventTimeStamp = 0
        startTime = time.time()
        timeToCheckForFile = time.time(
        ) + 1  # check if file exists at least every second
        while not fileExists:
            if timeout > 0 and time.time() > (startTime + timeout):
                return None
            # look for file creation event
            eventLoopCount += 1
            try:
                event, ts = self.fileNotifyQ.get(block=True, timeout=1.0)
            except Empty as err:
                # The timeout occured on fileNotifyQ.get()
                fileExists = os.path.exists(specificFileName)
                continue
            if event is None:
                raise StateError('waitForFile: event is None')
            # We may have a stale event from a previous file if multiple events
            #   are created per file or if the previous file eventloop
            #   timed out and then the event arrived later.
            if event.src_path == specificFileName:
                fileExists = True
                exitWithFileEvent = True
                eventTimeStamp = ts
                continue
            if time.time() > timeToCheckForFile:
                # periodically check if file exists, can occur if we get
                #   swamped with unrelated events
                fileExists = os.path.exists(specificFileName)
                timeToCheckForFile = time.time() + 1

        # wait for the full file to be written, wait at most 300 ms
        waitIncrement = 0.1
        totalWriteWait = 0.0
        fileSize = os.path.getsize(specificFileName)
        while fileSize < self.minFileSize and totalWriteWait < 0.3:
            time.sleep(waitIncrement)
            totalWriteWait += waitIncrement
            fileSize = os.path.getsize(specificFileName)
        logging.log(
            DebugLevels.L6,
            "File avail: eventLoopCount %d, writeWaitTime %.3f, "
            "fileEventCaptured %s, fileName %s, eventTimeStamp %.5f",
            eventLoopCount, totalWriteWait, exitWithFileEvent,
            specificFileName, eventTimeStamp)
        if self.demoStep is not None and self.demoStep > 0:
            self.prevEventTime = demoDelay(self.demoStep, self.prevEventTime)
        return specificFileName