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


Python BytesIO.close方法代码示例

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


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

示例1: output_properties

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import close [as 别名]
def output_properties(path=None, content=None, basename=None, pseduo_location=False):
    checksum = hashlib.sha1()
    properties = {
        "class": "File",
    }
    if path is not None:
        properties["path"] = path
        f = open(path, "rb")
    else:
        f = BytesIO(content)

    try:
        contents = f.read(1024 * 1024)
        filesize = 0
        while contents:
            checksum.update(contents)
            filesize += len(contents)
            contents = f.read(1024 * 1024)
    finally:
        f.close()
    properties["checksum"] = "sha1$%s" % checksum.hexdigest()
    properties["size"] = filesize
    set_basename_and_derived_properties(properties, basename)
    _handle_pseudo_location(properties, pseduo_location)
    return properties
开发者ID:ImmPortDB,项目名称:immport-galaxy,代码行数:27,代码来源:util.py

示例2: test_write

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import close [as 别名]
    def test_write(self):
        r = StringIO('ab')
        n = FrenchNormalizer(r)
        m = Matrix()
        w = BytesIO()

        m.feed(n)
        m.dump(w)

        expected = {
            (None,): {
                False: 1,
            },
            (False,): {
                'a': 1,
            },
            ('a',): {
                'b': 1,
            },
            ('b',): {
                True: 1
            }
        }

        print(pickle.loads(w.getvalue()))
        print(expected)

        assert pickle.loads(w.getvalue()) == expected
        w.close()
开发者ID:Xowap,项目名称:gibi,代码行数:31,代码来源:matrix.py

示例3: compress

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import close [as 别名]
def compress(data):
    """
    Compresses given data via the snappy algorithm.

    The result is preceded with a header containing the string 'SNAPPY' and the
    default and min-compat versions (both ``1``).

    The block size for the compression is hard-coded at 32kb.

    If ``python-snappy`` is not installed a ``RuntimeError`` is raised.
    """
    if not snappy_available:
        raise RuntimeError("Snappy compression unavailable.")

    buff = BytesIO()
    buff.write(raw_header)

    for block_num in range(0, len(data), BLOCK_SIZE):
        block = data[block_num:block_num + BLOCK_SIZE]
        compressed = snappy.compress(block)

        buff.write(struct.pack("!i", len(compressed)))
        buff.write(compressed)

    result = buff.getvalue()

    buff.close()

    return result
开发者ID:FlorianLudwig,项目名称:kiel,代码行数:31,代码来源:snappy.py

示例4: __init__

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import close [as 别名]
    def __init__(self, host, port, backend_mod=None, pool=None,
                 is_ssl=False, extra_headers=[], proxy_pieces=None, **ssl_args):

        # connect the socket, if we are using an SSL connection, we wrap
        # the socket.
        self._s = backend_mod.Socket(socket.AF_INET, socket.SOCK_STREAM)
        self._s.connect((host, port))
        if proxy_pieces:
            self._s.sendall(proxy_pieces)
            response = StringIO()
            while response.getvalue()[-4:] != b'\r\n\r\n':
                response.write(self._s.recv(1))
            response.close()
        if is_ssl:
            self._s = ssl.wrap_socket(self._s, **ssl_args)

        self.extra_headers = extra_headers
        self.is_ssl = is_ssl
        self.backend_mod = backend_mod
        self.host = host
        self.port = port
        self._connected = True
        self._life = time.time() - random.randint(0, 10)
        self._pool = pool
        self._released = False
开发者ID:pashinin,项目名称:restkit,代码行数:27,代码来源:conn.py

示例5: decompress

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import close [as 别名]
def decompress(data):
    """
    Decompresses the given data via the snappy algorithm.

    If ``python-snappy`` is not installed a ``RuntimeError`` is raised.
    """
    if not snappy_available:
        raise RuntimeError("Snappy compression unavailable.")

    buff_offset = len(raw_header)  # skip the header
    length = len(data) - len(raw_header)

    output = BytesIO()

    while buff_offset <= length:
        block_size = struct.unpack_from("!i", data, buff_offset)[0]
        buff_offset += struct.calcsize("!i")

        block = struct.unpack_from("!%ds" % block_size, data, buff_offset)[0]
        buff_offset += block_size

        output.write(snappy.uncompress(block))

    result = output.getvalue()

    output.close()

    return result
开发者ID:FlorianLudwig,项目名称:kiel,代码行数:30,代码来源:snappy.py

示例6: test_decode_response_gzip

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import close [as 别名]
def test_decode_response_gzip():
    body = b'gzip message'

    buf = BytesIO()
    f = gzip.GzipFile('a', fileobj=buf, mode='wb')
    f.write(body)
    f.close()

    compressed_body = buf.getvalue()
    buf.close()
    gzip_response = {
        'body': {'string': compressed_body},
        'headers': {
            'access-control-allow-credentials': ['true'],
            'access-control-allow-origin': ['*'],
            'connection': ['keep-alive'],
            'content-encoding': ['gzip'],
            'content-length': ['177'],
            'content-type': ['application/json'],
            'date': ['Wed, 02 Dec 2015 19:44:32 GMT'],
            'server': ['nginx']
        },
        'status': {'code': 200, 'message': 'OK'}
    }
    decoded_response = decode_response(gzip_response)
    assert decoded_response['body']['string'] == body
    assert decoded_response['headers']['content-length'] == [str(len(body))]
开发者ID:JanLikar,项目名称:vcrpy,代码行数:29,代码来源:test_filters.py

示例7: serialize

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import close [as 别名]
    def serialize(
            self, destination=None, encoding="utf-8", format='xml', **args):

        if self.type in ('CONSTRUCT', 'DESCRIBE'):
            return self.graph.serialize(
                destination, encoding=encoding, format=format, **args)

        """stolen wholesale from graph.serialize"""
        from rdflib import plugin
        serializer = plugin.get(format, ResultSerializer)(self)
        if destination is None:
            stream = BytesIO()
            stream2 = EncodeOnlyUnicode(stream)
            serializer.serialize(stream2, encoding=encoding, **args)
            return stream.getvalue()
        if hasattr(destination, "write"):
            stream = destination
            serializer.serialize(stream, encoding=encoding, **args)
        else:
            location = destination
            scheme, netloc, path, params, query, fragment = urlparse(location)
            if netloc != "":
                print("WARNING: not saving as location" +
                      "is not a local file reference")
                return
            fd, name = tempfile.mkstemp()
            stream = os.fdopen(fd, 'wb')
            serializer.serialize(stream, encoding=encoding, **args)
            stream.close()
            if hasattr(shutil, "move"):
                shutil.move(name, path)
            else:
                shutil.copy(name, path)
                os.remove(name)
开发者ID:drewp,项目名称:rdflib,代码行数:36,代码来源:query.py

示例8: test_writing_1_record

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import close [as 别名]
 def test_writing_1_record(self):
     expected = r"""
         <?xml version="1.0" encoding="UTF-8"?>
         <collection xmlns="http://www.loc.gov/MARC21/slim">
         <record>
         <leader>          22        4500</leader>
         <datafield ind1="0" ind2="0" tag="100">
         <subfield code="a">me</subfield>
         </datafield>
         <datafield ind1="0" ind2="0" tag="245">
         <subfield code="a">Foo /</subfield>
         <subfield code="c">by me.</subfield>
         </datafield>
         </record>
         </collection>
     """
     expected = textwrap.dedent(expected[1:]).replace('\n', '')
     if str != binary_type:
         expected = expected.encode()
     file_handle = BytesIO()
     try:
         writer = pymarc.XMLWriter(file_handle)
         record = pymarc.Record()
         record.add_field(
             pymarc.Field('100', ['0', '0'], ['a', u('me')]))
         record.add_field(
             pymarc.Field(
                 '245',
                 ['0', '0'],
                 ['a', u('Foo /'), 'c', u('by me.')]))
         writer.write(record)
         writer.close(close_fh=False)
         self.assertEquals(file_handle.getvalue(), expected)
     finally:
         file_handle.close()
开发者ID:EdwardBetts,项目名称:pymarc,代码行数:37,代码来源:writer.py

示例9: __iter__

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import close [as 别名]
 def __iter__(self):
     if self.is_zipped:
         byte_stream = BytesIO(self.response.content)
         with zipfile.ZipFile(byte_stream) as self.zipfile:
             for name in self.zipfile.namelist():
                 with self.zipfile.open(name) as single_file:
                     if name[-3:] == 'csv':
                         reader = csv.reader(single_file, delimiter=self.delimiter)
                     else:
                         reader = single_file
                     reader_iterator = iter(reader)
                     if self.is_header_present:
                         next(reader_iterator)
                     for line in reader_iterator:
                         yield self._parse_line(line)
         byte_stream.close()
     else:
         stream = codecs.iterdecode(self.response.iter_lines(),
                                    self.response.encoding or self.response.apparent_encoding)
         reader = csv.reader(stream, delimiter=self.delimiter)
         reader_iterator = iter(reader)
         if self.is_header_present:
             next(reader_iterator)
         for line in reader_iterator:
             yield self._parse_line(line)
         stream.close()
开发者ID:PraveenAdlakha,项目名称:lens,代码行数:28,代码来源:query.py

示例10: visit_immutation

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import close [as 别名]
    def visit_immutation(self, node, children):
        context = self._final_context()
        child_type = children[0].expr_name

        if child_type == 'preview':
            if self.tool == 'httpie':
                command = ['http'] + context.httpie_args(self.method,
                                                         quote=True)
            else:
                assert self.tool == 'curl'
                command = ['curl'] + context.curl_args(self.method, quote=True)
            click.echo(' '.join(command))
        elif child_type == 'action':
            output = BytesIO()
            try:
                env = Environment(stdout=output, is_windows=False)
                httpie_main(context.httpie_args(self.method), env=env)
                content = output.getvalue()
            finally:
                output.close()

            # XXX: Work around a bug of click.echo_via_pager(). When you pass
            # a bytestring to echo_via_pager(), it converts the bytestring with
            # str(b'abc'), which makes it "b'abc'".
            if six.PY2:
                content = unicode(content, 'utf-8')  # noqa
            else:
                content = str(content, 'utf-8')
            click.echo_via_pager(content)

        return node
开发者ID:JethroTseng,项目名称:http-prompt,代码行数:33,代码来源:execution.py

示例11: image_to_png

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import close [as 别名]
def image_to_png(img):
    """Convert a PIL image to a PNG binary string."""
    exp = BytesIO()
    img.save(exp, format='png')
    exp.seek(0)
    s = exp.read()
    exp.close()
    return s
开发者ID:vins31,项目名称:smopy,代码行数:10,代码来源:smopy.py

示例12: test_safe_md5

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import close [as 别名]
    def test_safe_md5(self):
        exp = 'ab07acbb1e496801937adfa772424bf7'

        fd = BytesIO(b'foo bar baz')
        obs = safe_md5(fd)
        self.assertEqual(obs.hexdigest(), exp)

        fd.close()
开发者ID:ebolyen,项目名称:scikit-bio,代码行数:10,代码来源:test_misc.py

示例13: test_safe_md5

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import close [as 别名]
    def test_safe_md5(self):
        """Make sure we have the expected md5"""
        exp = 'ab07acbb1e496801937adfa772424bf7'

        fd = BytesIO(b'foo bar baz')
        obs = safe_md5(fd)
        self.assertEqual(obs.hexdigest(), exp)

        fd.close()
开发者ID:jradinger,项目名称:scikit-bio,代码行数:11,代码来源:test_misc.py

示例14: test_50_get

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import close [as 别名]
    def test_50_get(self):
        io = BytesIO()
        self.webdav.download('handler.py', io)
        self.assertEqual(utils.text(inspect.getsource(data_handler)), utils.text(io.getvalue()))
        io.close()

        io = BytesIO()
        self.webdav.download('sample_handler.py', io)
        self.assertEqual(utils.text(inspect.getsource(data_sample_handler)), utils.text(io.getvalue()))
        io.close()
开发者ID:Dmitry-Kucher,项目名称:pyspider,代码行数:12,代码来源:test_webdav.py

示例15: check_binary

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import close [as 别名]
def check_binary(name, file_path=True):
    # Handles files if file_path is True or text if file_path is False
    if file_path:
        temp = open(name, "rb")
    else:
        temp = BytesIO(name)
    try:
        return util.is_binary(temp.read(1024))
    finally:
        temp.close()
开发者ID:lappsgrid-incubator,项目名称:Galaxy,代码行数:12,代码来源:checkers.py


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