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


Python six.BytesIO方法代码示例

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


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

示例1: testLeapCountDecodesProperly

# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def testLeapCountDecodesProperly(self):
        # This timezone has leapcnt, and failed to decode until
        # Eugene Oden notified about the issue.

        # As leap information is currently unused (and unstored) by tzfile() we
        # can only indirectly test this: Take advantage of tzfile() not closing
        # the input file if handed in as an opened file and assert that the
        # full file content has been read by tzfile(). Note: For this test to
        # work NEW_YORK must be in TZif version 1 format i.e. no more data
        # after TZif v1 header + data has been read
        fileobj = BytesIO(base64.b64decode(NEW_YORK))
        tz.tzfile(fileobj)
        # we expect no remaining file content now, i.e. zero-length; if there's
        # still data we haven't read the file format correctly
        remaining_tzfile_content = fileobj.read()
        self.assertEqual(len(remaining_tzfile_content), 0) 
开发者ID:MediaBrowser,项目名称:plugin.video.emby,代码行数:18,代码来源:test_tz.py

示例2: keep_file

# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def keep_file(self, task, response, min_size=None, max_size=None):
        """Decide whether to keep the image

        Compare image size with ``min_size`` and ``max_size`` to decide.

        Args:
            response (Response): response of requests.
            min_size (tuple or None): minimum size of required images.
            max_size (tuple or None): maximum size of required images.
        Returns:
            bool: whether to keep the image.
        """
        try:
            img = Image.open(BytesIO(response.content))
        except (IOError, OSError):
            return False
        task['img_size'] = img.size
        if min_size and not self._size_gt(img.size, min_size):
            return False
        if max_size and not self._size_lt(img.size, max_size):
            return False
        return True 
开发者ID:hellock,项目名称:icrawler,代码行数:24,代码来源:downloader.py

示例3: unpacked

# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def unpacked(cls, raw):
        # B = unsigned char
        # !I = network-order (big-endian) unsigned int
        raw = six.BytesIO(raw)
        raw_chars = raw.read(4)
        if raw_chars:
            version, type, seq_no, flags = struct.unpack(
                'BBBB',
                raw_chars
            )
            session_id, length = struct.unpack('!II', raw.read(8))
            return cls(version, type, session_id, length, seq_no, flags)
        else:
            raise ValueError(
                "Unable to extract data from header. Likely the TACACS+ key does not match between server and client"
            ) 
开发者ID:ansible,项目名称:tacacs_plus,代码行数:18,代码来源:packet.py

示例4: unpacked

# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def unpacked(cls, raw):
        # 1 2 3 4 5 6 7 8  1 2 3 4 5 6 7 8  1 2 3 4 5 6 7 8  1 2 3 4 5 6 7 8
        #
        # +----------------+----------------+----------------+----------------+
        # |     status     |      flags     |        server_msg len           |
        # +----------------+----------------+----------------+----------------+
        # |           data len              |        server_msg ...
        # +----------------+----------------+----------------+----------------+
        # |           data ...
        # +----------------+----------------+

        # B = unsigned char
        # !H = network-order (big-endian) unsigned short
        raw = six.BytesIO(raw)
        status, flags = struct.unpack('BB', raw.read(2))
        server_msg_len, data_len = struct.unpack('!HH', raw.read(4))
        server_msg = raw.read(server_msg_len)
        data = raw.read(data_len)
        return cls(status, flags, server_msg, data) 
开发者ID:ansible,项目名称:tacacs_plus,代码行数:21,代码来源:authentication.py

示例5: unpacked

# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def unpacked(cls, raw):
        #  1 2 3 4 5 6 7 8  1 2 3 4 5 6 7 8  1 2 3 4 5 6 7 8  1 2 3 4 5 6 7 8
        # +----------------+----------------+----------------+----------------+
        # |         server_msg len          |            data_len             |
        # +----------------+----------------+----------------+----------------+
        # |     status     |         server_msg ...
        # +----------------+----------------+----------------+----------------+
        # |     data ...
        # +----------------+

        # B = unsigned char
        # !H = network-order (big-endian) unsigned short
        raw = six.BytesIO(raw)
        server_msg_len, data_len = struct.unpack('!HH', raw.read(4))
        status = struct.unpack('B', raw.read(1))[0]
        server_msg = raw.read(server_msg_len)
        data = raw.read(data_len) if data_len else b''
        return cls(status, server_msg, data) 
开发者ID:ansible,项目名称:tacacs_plus,代码行数:20,代码来源:accounting.py

示例6: FigureToSummary

# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def FigureToSummary(name, fig):
  """Create tf.Summary proto from matplotlib.figure.Figure.

  Args:
    name: Summary name.
    fig: A matplotlib figure object.

  Returns:
    A `tf.Summary` proto containing the figure rendered to an image.
  """
  canvas = backend_agg.FigureCanvasAgg(fig)
  fig.canvas.draw()
  ncols, nrows = fig.canvas.get_width_height()
  png_file = six.BytesIO()
  canvas.print_figure(png_file)
  png_str = png_file.getvalue()
  return tf.Summary(value=[
      tf.Summary.Value(
          tag='%s/image' % name,
          image=tf.Summary.Image(
              height=nrows,
              width=ncols,
              colorspace=3,
              encoded_image_string=png_str))
  ]) 
开发者ID:tensorflow,项目名称:lingvo,代码行数:27,代码来源:plot.py

示例7: __getitem__

# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def __getitem__(self, index):
        img, target = None, None
        env = self.env
        with env.begin(write=False) as txn:
            imgbuf = txn.get(self.keys[index])

        buf = six.BytesIO()
        buf.write(imgbuf)
        buf.seek(0)
        img = Image.open(buf).convert('RGB')

        if self.transform is not None:
            img = self.transform(img)

        if self.target_transform is not None:
            target = self.target_transform(target)

        return img, target 
开发者ID:hendrycks,项目名称:pre-training,代码行数:20,代码来源:lsun_loader.py

示例8: _generate_time_steps

# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def _generate_time_steps(self, trajectory_list):
    """Transforms time step observations to frames of a video."""
    for time_step in gym_env_problem.GymEnvProblem._generate_time_steps(
        self, trajectory_list):
      # Convert the rendered observations from numpy to png format.
      frame_np = np.array(time_step.pop(env_problem.OBSERVATION_FIELD))
      frame_np = frame_np.reshape(
          [self.frame_height, self.frame_width, self.num_channels])
      # TODO(msaffar) Add support for non RGB rendered environments
      frame = png.from_array(frame_np, "RGB", info={"bitdepth": 8})
      frame_buffer = six.BytesIO()
      frame.save(frame_buffer)

      # Put the encoded frame back.
      time_step[_IMAGE_ENCODED_FIELD] = [frame_buffer.getvalue()]
      time_step[_IMAGE_FORMAT_FIELD] = [_FORMAT]
      time_step[_IMAGE_HEIGHT_FIELD] = [self.frame_height]
      time_step[_IMAGE_WIDTH_FIELD] = [self.frame_width]

      # Add the frame number
      time_step[_FRAME_NUMBER_FIELD] = time_step[env_problem.TIMESTEP_FIELD]
      yield time_step 
开发者ID:tensorflow,项目名称:tensor2tensor,代码行数:24,代码来源:rendered_env_problem.py

示例9: load

# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def load(f, persistent_load=PersistentNdarrayLoad):
    """Load a file that was dumped to a zip file.

    :param f: The file handle to the zip file to load the object from.
    :type f: file

    :param persistent_load: The persistent loading function to use for
        unpickling. This must be compatible with the `persisten_id` function
        used when pickling.
    :type persistent_load: callable, optional

    .. versionadded:: 0.8
    """
    with closing(zipfile.ZipFile(f, 'r')) as zip_file:
        p = pickle.Unpickler(BytesIO(zip_file.open('pkl').read()))
        p.persistent_load = persistent_load(zip_file)
        return p.load() 
开发者ID:muhanzhang,项目名称:D-VAE,代码行数:19,代码来源:pkl_utils.py

示例10: test_serialize_and_deserialize_multi_np

# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def test_serialize_and_deserialize_multi_np():
    x = np.random.random((1, ))
    y = np.random.random((2, 3))
    z = np.random.random((1, 5, 2))
    values = {'x': x, 'y': y, 'z': z}

    # write out values in x
    f = BytesIO()
    serde_weights.write_np_values(values, f)

    # reset file so it appears to be freshly opened for deserialize_weights
    f.seek(0)
    de_values = serde_weights.read_np_values(f)

    assert values.keys() == de_values.keys()
    for k, v in values.items():
        assert (de_values[k] == v).all() 
开发者ID:NervanaSystems,项目名称:ngraph-python,代码行数:19,代码来源:test_serde_weights.py

示例11: test_read_file

# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def test_read_file(self):
        ASSET_FILE_NAMES =  [u'Read.txt', u'读.txt']
        for assert_file_name in ASSET_FILE_NAMES:
            REMOTE_PATH = join(UNIQUE_PATH, assert_file_name)

            test_file = six.BytesIO()
            test_file.write(u"你好世界 Hello World".encode('utf-8'))
            test_file.seek(0)
            self.storage.save(REMOTE_PATH, test_file)

            fil = self.storage.open(REMOTE_PATH, 'r')

            assert fil._is_read == False

            content = fil.read()
            assert content.startswith(u"你好")

            assert fil._is_read == True

            # Test open mode
            fil = self.storage.open(REMOTE_PATH, 'rb')
            bin_content = fil.read()
            assert bin_content.startswith(u"你好".encode('utf-8')) 
开发者ID:glasslion,项目名称:django-qiniu-storage,代码行数:25,代码来源:test_storage.py

示例12: GetProperty

# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def GetProperty(self, value_mask, items, is_checked=True):
        buf = six.BytesIO()
        buf.write(struct.pack("=xx2xI", value_mask))
        if value_mask & CA.Counter:
            counter = items.pop(0)
            buf.write(struct.pack("=I", counter))
        if value_mask & CA.Value:
            value = items.pop(0)
            buf.write(value.pack() if hasattr(value, "pack") else INT64.synthetic(*value).pack())
        if value_mask & CA.ValueType:
            valueType = items.pop(0)
            buf.write(struct.pack("=I", valueType))
        if value_mask & CA.Events:
            events = items.pop(0)
            buf.write(struct.pack("=I", events))
        return self.send_request(59, buf, GetPropertyCookie, is_checked=is_checked) 
开发者ID:tych0,项目名称:xcffib,代码行数:18,代码来源:switch.py

示例13: test_50_get

# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [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:binux,项目名称:pyspider,代码行数:12,代码来源:test_webdav.py

示例14: encode_image_array_as_png_str

# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def encode_image_array_as_png_str(image):
  """Encodes a numpy array into a PNG string.

  Args:
    image: a numpy array with shape [height, width, 3].

  Returns:
    PNG encoded image string.
  """
  image_pil = Image.fromarray(np.uint8(image))
  output = six.BytesIO()
  image_pil.save(output, format='PNG')
  png_string = output.getvalue()
  output.close()
  return png_string 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:17,代码来源:visualization_utils.py

示例15: decode_img_from_buf

# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def decode_img_from_buf(buf, backend='cv2'):
    if backend == 'pil':
        buf = six.BytesIO(buf)
        img = Image.open(buf).convert('RGB')
    elif backend == 'cv2':
        buf = np.frombuffer(buf, np.uint8)
        img = cv2.imdecode(buf, 1)[..., ::-1]
    else:
        raise NotImplementedError
    return img 
开发者ID:PistonY,项目名称:torch-toolbox,代码行数:12,代码来源:utils.py


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