当前位置: 首页>>代码示例>>Python>>正文


Python BufferedReader.close方法代码示例

本文整理汇总了Python中io.BufferedReader.close方法的典型用法代码示例。如果您正苦于以下问题:Python BufferedReader.close方法的具体用法?Python BufferedReader.close怎么用?Python BufferedReader.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在io.BufferedReader的用法示例。


在下文中一共展示了BufferedReader.close方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: tst_io_bufferedreader

# 需要导入模块: from io import BufferedReader [as 别名]
# 或者: from io.BufferedReader import close [as 别名]
    def tst_io_bufferedreader(self):

        fp = self._fake_fp(b'foo')
        #fp = BytesIO(b'foo')
        resp = HTTPResponse(fp, preload_content=False)
        br = BufferedReader(resp)

        self.assertEqual(br.read(), b'foo')

        br.close()
        self.assertEqual(resp.closed, True)

        b = b'fooandahalf'
        fp = self._fake_fp(b)
        #fp = BytesIO(b)
        resp = HTTPResponse(fp, preload_content=False)
        br = BufferedReader(resp, 5)

        br.read(1)  # sets up the buffer, reading 5
        self.assertEqual(len(fp.read()), len(b) - 5)

        # This is necessary to make sure the "no bytes left" part of `readinto`
        # gets tested.
        while not br.closed:
            br.read(5)
开发者ID:rdbhost,项目名称:yieldfromUrllib3,代码行数:27,代码来源:test_response.py

示例2: test_io_bufferedreader

# 需要导入模块: from io import BufferedReader [as 别名]
# 或者: from io.BufferedReader import close [as 别名]
    def test_io_bufferedreader(self):
        fp = BytesIO(b'foo')
        resp = HTTPResponse(fp, preload_content=False)
        br = BufferedReader(resp)

        self.assertEqual(br.read(), b'foo')

        br.close()
        self.assertEqual(resp.closed, True)
开发者ID:Mofangbao,项目名称:urllib3,代码行数:11,代码来源:test_response.py

示例3: read

# 需要导入模块: from io import BufferedReader [as 别名]
# 或者: from io.BufferedReader import close [as 别名]
    def read(self, file_path):
        while not self.writing:
            time.sleep(1)

        print "Read starting..."

        f = ASIO.open(file_path, opener=False)
        s = BufferedReader(f)

        orig_path = f.get_path()
        stale_since = None

        while True:
            if f is None:
                print 'Opening file...'
                f = ASIO.open(file_path, opener=False)
                s = BufferedReader(f)

            # Try read line
            line = s.readline()

            if line:
                stale_since = None
                time.sleep(0.05)
            else:
                if stale_since is None:
                    stale_since = time.time()
                    time.sleep(0.1)
                    continue
                elif (time.time() - stale_since) > 2 and f.get_path() != orig_path:
                    s.close()
                    s = None

                    f.close()
                    f = None
                elif not self.writing:
                    break
                else:
                    time.sleep(0.1)
                    continue

            print 'read %r' % (line,)

        print 'finished'
        s.close()
        f.close()
开发者ID:fuzeman,项目名称:ASIO,代码行数:48,代码来源:test_log_rotation.py

示例4: test_io_bufferedreader

# 需要导入模块: from io import BufferedReader [as 别名]
# 或者: from io.BufferedReader import close [as 别名]
    def test_io_bufferedreader(self):
        fp = BytesIO(b'foo')
        resp = HTTPResponse(fp, preload_content=False)
        br = BufferedReader(resp)

        assert br.read() == b'foo'

        br.close()
        assert resp.closed

        b = b'fooandahalf'
        fp = BytesIO(b)
        resp = HTTPResponse(fp, preload_content=False)
        br = BufferedReader(resp, 5)

        br.read(1)  # sets up the buffer, reading 5
        assert len(fp.read()) == (len(b) - 5)

        # This is necessary to make sure the "no bytes left" part of `readinto`
        # gets tested.
        while not br.closed:
            br.read(5)
开发者ID:jonparrott,项目名称:urllib3,代码行数:24,代码来源:test_response.py

示例5: __init__

# 需要导入模块: from io import BufferedReader [as 别名]
# 或者: from io.BufferedReader import close [as 别名]

#.........这里部分代码省略.........
            length = first_byte
            padding = (length + 1) % 4

        data = self.read(length)
        if padding > 0:
            padding = 4 - padding
            self.read(padding)

        return data

    def tgread_string(self):
        """Reads a Telegram-encoded string."""
        return str(self.tgread_bytes(), encoding='utf-8', errors='replace')

    def tgread_bool(self):
        """Reads a Telegram boolean value."""
        value = self.read_int(signed=False)
        if value == 0x997275b5:  # boolTrue
            return True
        elif value == 0xbc799737:  # boolFalse
            return False
        else:
            raise RuntimeError('Invalid boolean code {}'.format(hex(value)))

    def tgread_date(self):
        """Reads and converts Unix time (used by Telegram)
           into a Python datetime object.
        """
        value = self.read_int()
        if value == 0:
            return None
        else:
            return datetime.fromtimestamp(value, tz=timezone.utc)

    def tgread_object(self):
        """Reads a Telegram object."""
        constructor_id = self.read_int(signed=False)
        clazz = tlobjects.get(constructor_id, None)
        if clazz is None:
            # The class was None, but there's still a
            # chance of it being a manually parsed value like bool!
            value = constructor_id
            if value == 0x997275b5:  # boolTrue
                return True
            elif value == 0xbc799737:  # boolFalse
                return False
            elif value == 0x1cb5c415:  # Vector
                return [self.tgread_object() for _ in range(self.read_int())]

            clazz = core_objects.get(constructor_id, None)
            if clazz is None:
                # If there was still no luck, give up
                self.seek(-4)  # Go back
                pos = self.tell_position()
                error = TypeNotFoundError(constructor_id, self.read())
                self.set_position(pos)
                raise error

        return clazz.from_reader(self)

    def tgread_vector(self):
        """Reads a vector (a list) of Telegram objects."""
        if 0x1cb5c415 != self.read_int(signed=False):
            raise RuntimeError('Invalid constructor code, vector was expected')

        count = self.read_int()
        return [self.tgread_object() for _ in range(count)]

    # endregion

    def close(self):
        """Closes the reader, freeing the BytesIO stream."""
        self.reader.close()

    # region Position related

    def tell_position(self):
        """Tells the current position on the stream."""
        return self.reader.tell()

    def set_position(self, position):
        """Sets the current position on the stream."""
        self.reader.seek(position)

    def seek(self, offset):
        """
        Seeks the stream position given an offset from the current position.
        The offset may be negative.
        """
        self.reader.seek(offset, os.SEEK_CUR)

    # endregion

    # region with block

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()
开发者ID:leanderdulac,项目名称:Telethon,代码行数:104,代码来源:binaryreader.py

示例6: Logging

# 需要导入模块: from io import BufferedReader [as 别名]
# 或者: from io.BufferedReader import close [as 别名]
class Logging(Source):
    name = 'logging'
    events = [
        'logging.playing',
        'logging.action.played',
        'logging.action.unplayed'
    ]

    parsers = []

    path = None
    path_hints = PATH_HINTS

    def __init__(self, activity):
        super(Logging, self).__init__()

        self.parsers = [p(self) for p in Logging.parsers]

        self.file = None
        self.reader = None

        self.path = None

        # Pipe events to the main activity instance
        self.pipe(self.events, activity)

    def run(self):
        line = self.read_line_retry(ping=True, stale_sleep=0.5)
        if not line:
            log.info('Unable to read log file')
            return

        log.debug('Ready')

        while True:
            # Grab the next line of the log
            line = self.read_line_retry(ping=True)

            if line:
                self.process(line)
            else:
                log.info('Unable to read log file')

    def process(self, line):
        for parser in self.parsers:
            if parser.process(line):
                return True

        return False

    def read_line(self):
        if not self.file:
            path = self.get_path()
            if not path:
                raise Exception('Unable to find the location of "Plex Media Server.log"')

            # Open file
            self.file = ASIO.open(path, opener=False)
            self.file.seek(self.file.get_size(), SEEK_ORIGIN_CURRENT)

            # Create buffered reader
            self.reader = BufferedReader(self.file)

            self.path = self.file.get_path()
            log.info('Opened file path: "%s"' % self.path)

        return self.reader.readline()

    def read_line_retry(self, timeout=60, ping=False, stale_sleep=1.0):
        line = None
        stale_since = None

        while not line:
            line = self.read_line()

            if line:
                stale_since = None
                time.sleep(0.05)
                break

            if stale_since is None:
                stale_since = time.time()
                time.sleep(stale_sleep)
                continue
            elif (time.time() - stale_since) > timeout:
                return None
            elif (time.time() - stale_since) > timeout / 2:
                # Nothing returned for 5 seconds
                if self.file.get_path() != self.path:
                    log.debug("Log file moved (probably rotated), closing")
                    self.close()
                elif ping:
                    # Ping server to see if server is still active
                    Plex.detail()
                    ping = False

            time.sleep(stale_sleep)

        return line

#.........这里部分代码省略.........
开发者ID:Danik1601,项目名称:Plex-Trakt-Scrobbler,代码行数:103,代码来源:main.py


注:本文中的io.BufferedReader.close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。