當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。