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


Python struct.html方法代码示例

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


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

示例1: unpack

# 需要导入模块: import struct [as 别名]
# 或者: from struct import html [as 别名]
def unpack(self, fmt, length=1):
        """
        Unpack the stream contents according to the specified format in `fmt`.
        For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html

        Args:
            fmt (str): format string.
            length (int): amount of bytes to read.

        Returns:
            variable: the result according to the specified format.
        """
        try:
            info = struct.unpack(fmt, self.stream.read(length))[0]
        except struct.error as e:
            raise SDKException(ErrorCode.unpack_error(e.args[0]))
        return info 
开发者ID:ontio,项目名称:ontology-python-sdk,代码行数:19,代码来源:binary_reader.py

示例2: read_var_int

# 需要导入模块: import struct [as 别名]
# 或者: from struct import html [as 别名]
def read_var_int(self, max_size=sys.maxsize):
        """
        Read a variable length integer from the stream.
        The NEO network protocol supports encoded storage for space saving. See: http://docs.neo.org/en-us/node/network-protocol.html#convention

        Args:
            max_size (int): (Optional) maximum number of bytes to read.

        Returns:
            int:
        """
        fb = self.read_byte()
        if fb is 0:
            return fb
        if hex(fb) == '0xfd':
            value = self.read_uint16()
        elif hex(fb) == '0xfe':
            value = self.read_uint32()
        elif hex(fb) == '0xff':
            value = self.read_uint64()
        else:
            value = fb
        if value > max_size:
            raise SDKException(ErrorCode.param_err('Invalid format'))
        return int(value) 
开发者ID:ontio,项目名称:ontology-python-sdk,代码行数:27,代码来源:binary_reader.py

示例3: _i2c_query

# 需要导入模块: import struct [as 别名]
# 或者: from struct import html [as 别名]
def _i2c_query(self, address, format):
        """Reads an i2c value from given address, and returns a value unpacked
        according to the given format. Format is the same as in the struct
        module. See http://docs.python.org/library/struct.html#format-strings
        """
        n_bytes = struct.calcsize(format)
        msg = bytes((self.I2C_DEV, address))
        now = time()
        if self.last_poll+self.poll_delay > now:
            diff = now - self.last_poll
            sleep(self.poll_delay - diff)
        self.last_poll = time()
        self.brick.ls_write(self.port, msg, n_bytes)
        try:
            self._ls_get_status(n_bytes)
        finally:
            #we should clear the buffer no matter what happens
            data = self.brick.ls_read(self.port)
        if len(data) < n_bytes:
            raise I2CError('Read failure: Not enough bytes')
        data = struct.unpack(format, data[-n_bytes:])
        return data 
开发者ID:Eelviny,项目名称:nxt-python,代码行数:24,代码来源:digital.py

示例4: ReadVarBytes

# 需要导入模块: import struct [as 别名]
# 或者: from struct import html [as 别名]
def ReadVarBytes(self, max=sys.maxsize):
        """
        Read a variable length of bytes from the stream.
        The NEO network protocol supports encoded storage for space saving. See: http://docs.neo.org/en-us/node/network-protocol.html#convention

        Args:
            max (int): (Optional) maximum number of bytes to read.

        Raises:
            ValueError: if the amount of bytes indicated by the variable int cannot be read

        Returns:
            bytes:
        """
        length = self.ReadVarInt(max)
        return self.SafeReadBytes(length) 
开发者ID:CityOfZion,项目名称:neo-python,代码行数:18,代码来源:BinaryReader.py

示例5: WriteVarString

# 需要导入模块: import struct [as 别名]
# 或者: from struct import html [as 别名]
def WriteVarString(self, value, encoding="utf-8"):
        """
        Write a string value to the stream.
        Read more about variable size encoding here: http://docs.neo.org/en-us/node/network-protocol.html#convention

        Args:
            value (string): value to write to the stream.
            encoding (str): string encoding format.
        """
        if type(value) is str:
            value = value.encode(encoding)

        length = len(value)
        ba = bytearray(value)
        byts = binascii.hexlify(ba)
        string = byts.decode(encoding)
        self.WriteVarInt(length)
        self.WriteBytes(string) 
开发者ID:CityOfZion,项目名称:neo-python,代码行数:20,代码来源:BinaryWriter.py

示例6: _unpack

# 需要导入模块: import struct [as 别名]
# 或者: from struct import html [as 别名]
def _unpack(self, fmt, length=1) -> Any:
        """
        Unpack the stream contents according to the specified format in `fmt`.
        For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html

        Args:
            fmt (str): format string.
            length (int): amount of bytes to read.

        Returns:
            variable: the result according to the specified format.
        """
        try:
            values = struct.unpack(fmt, self._stream.read(length))
            return values[0]
        except struct.error as e:
            raise ValueError(e) 
开发者ID:CityOfZion,项目名称:neo-python,代码行数:19,代码来源:binary_reader.py

示例7: bytesize

# 需要导入模块: import struct [as 别名]
# 或者: from struct import html [as 别名]
def bytesize(self, byteorder='@'):
        '''Compute the byte size after serialization.

        Args:
            byteorder (str, optional): This is byte order of the serialized data. Use one
                of the `byte order characters
                <https://docs.python.org/3/library/struct.html#byte-order-size-and-alignment>`_:
                ``@``, ``=``, ``<``, ``>``, and ``!``.
                Default is ``@`` -- the native order.

        Returns:
            int: Size in number of bytes after serialization.
        '''
        # Use 8 bytes to store the seed integer
        seed_size = struct.calcsize(byteorder+'q')
        # Use 4 bytes to store the number of hash values
        length_size = struct.calcsize(byteorder+'i')
        # Use 4 bytes to store each hash value as we are using the lower 32 bit
        hashvalue_size = struct.calcsize(byteorder+'I')
        return seed_size + length_size + len(self) * hashvalue_size 
开发者ID:ekzhu,项目名称:datasketch,代码行数:22,代码来源:lean_minhash.py

示例8: remote_run

# 需要导入模块: import struct [as 别名]
# 或者: from struct import html [as 别名]
def remote_run(self):
    """Start main loop and receive updates."""
    # Check connection
    if not self._session:
      self.connect()
    # We'll trade forever until interrupted
    logger.info("Starting main trading loop...")
    try:
      while True:
        socks = self._poller.poll(self.polltimeout)
        if not socks:
          continue
        raw = socks[0][0].recv()
        # unpack bytes https://docs.python.org/3/library/struct.html
        if len(raw) == 17:
          # We have tick data
          bid, ask = struct.unpack_from('dd', raw, 1) # offset topic
          self.on_tick(bid, ask, datetime.now())
        elif len(raw) == 33:
          # We have bar data
          bo, bh, bl, bc = struct.unpack_from('dddd', raw, 1) # offset topic
          self.on_bar(bo, bh, bl, bc, datetime.now())
    finally:
      logger.info("Stopping agent...")
      self.disconnect() 
开发者ID:nuric,项目名称:pedlar,代码行数:27,代码来源:agent.py

示例9: run

# 需要导入模块: import struct [as 别名]
# 或者: from struct import html [as 别名]
def run(self):
    """Connect to ticker server and emit updates."""
    socket = context.socket(zmq.SUB)
    # Set topic filter, this is a binary prefix
    # to check for each incoming message
    # set from server as uchar topic = X
    # We'll subsribe to only tick updates for now
    socket.setsockopt(zmq.SUBSCRIBE, bytes.fromhex('00'))
    with self.app.app_context():
      current_app.logger.debug("Connecting to ticker: %s", current_app.config['TICKER_URL'])
      socket.connect(current_app.config['TICKER_URL'])
      while True:
        raw = socket.recv()
        # unpack bytes https://docs.python.org/3/library/struct.html
        bid, ask = struct.unpack_from('dd', raw, 1) # offset topic
        self.socketio.emit('tick', {'bid': round(bid, 5), 'ask': round(ask, 5)})
    # socket will be cleaned up at garbarge collection 
开发者ID:nuric,项目名称:pedlar,代码行数:19,代码来源:flask_ticker.py

示例10: handle_tick

# 需要导入模块: import struct [as 别名]
# 或者: from struct import html [as 别名]
def handle_tick():
  """Listen to incoming tick updates."""
  socket = context.socket(zmq.SUB)
  # Set topic filter, this is a binary prefix
  # to check for each incoming message
  # set from server as uchar topic = X
  # We'll subsribe to only tick updates for now
  socket.setsockopt(zmq.SUBSCRIBE, bytes.fromhex('00'))
  logger.info("Connecting to ticker: %s", ARGS.ticker)
  socket.connect(ARGS.ticker)
  while True:
    raw = socket.recv()
    # unpack bytes https://docs.python.org/3/library/struct.html
    bid, ask = struct.unpack_from('dd', raw, 1) # offset topic
    logger.debug("Tick: %f %f", bid, ask)
    # We'll use global to pass tick data between green threads
    # since only 1 actually run at a time
    global BID, ASK # pylint: disable=global-statement
    BID, ASK = bid, ask
  # socket will be cleaned up at garbarge collection 
开发者ID:nuric,项目名称:pedlar,代码行数:22,代码来源:lbroker.py

示例11: pack

# 需要导入模块: import struct [as 别名]
# 或者: from struct import html [as 别名]
def pack(self, fmt, data):
        """
        Write bytes by packing them according to the provided format `fmt`.
        For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html
        """
        return self.write_bytes(struct.pack(fmt, data)) 
开发者ID:ontio,项目名称:ontology-python-sdk,代码行数:8,代码来源:binary_writer.py

示例12: _find_data_coding

# 需要导入模块: import struct [as 别名]
# 或者: from struct import html [as 别名]
def _find_data_coding(encoding):
        # NB:
        # We cant use all python standard encodings[1]
        # We can only use the ones defined in SMPP spec[2];
        #
        # 1. https://docs.python.org/3/library/codecs.html#standard-encodings
        # 2. section 5.2.19 of smpp ver 3.4 spec document.
        try:
            return SmppDataCoding.__dict__[encoding]
        except Exception as e:
            raise ValueError(
                "That encoding: `{0}` is not a recognised SMPP encoding.".format(encoding)
            ) from e 
开发者ID:komuw,项目名称:naz,代码行数:15,代码来源:state.py

示例13: from_value

# 需要导入模块: import struct [as 别名]
# 或者: from struct import html [as 别名]
def from_value(cls, value, size=None, fmt='Q', **kwargs):
        '''
        Factory method

        For format characters see: https://docs.python.org/2/library/struct.html
        '''
        bl = cls(**kwargs)  # size is 0 by default
        bl.fromvalue(value=value, size=size, fmt=fmt)
        return bl 
开发者ID:SiLab-Bonn,项目名称:basil,代码行数:11,代码来源:BitLogic.py

示例14: _start

# 需要导入模块: import struct [as 别名]
# 或者: from struct import html [as 别名]
def _start(self):
        # memoryview act as an recv buffer
        # refer https://docs.python.org/3/library/stdtypes.html#memoryview
        buff = memoryview(bytearray(RECV_BUFFER_SIZE))
        while True:
            if not self.conn_rd:
                # sleep if there is no connections
                time.sleep(0.06)
                continue

            # blocks until there is socket(s) ready for .recv
            # notice: sockets which were closed by remote,
            #   are also regarded as read-ready by select()
            r, w, e = select.select(self.conn_rd, [], [], 0.5)

            for s in r:  # iter every read-ready or closed sockets
                try:
                    # here, we use .recv_into() instead of .recv()
                    #   recv data directly into the pre-allocated buffer
                    #   to avoid many unnecessary malloc()
                    # see https://docs.python.org/3/library/socket.html#socket.socket.recv_into
                    rec_len = s.recv_into(buff, RECV_BUFFER_SIZE)
                except:
                    # unable to read, in most cases, it's due to socket close
                    self._rd_shutdown(s)
                    continue

                if not rec_len:
                    # read zero size, closed or shutdowned socket
                    self._rd_shutdown(s)
                    continue

                try:
                    # send data, we use `buff[:rec_len]` slice because
                    #   only the front of buff is filled
                    self.map[s].send(buff[:rec_len])
                except:
                    # unable to send, close connection
                    self._rd_shutdown(s)
                    continue 
开发者ID:mxdg,项目名称:passbytcp,代码行数:42,代码来源:common_func.py

示例15: decode_string

# 需要导入模块: import struct [as 别名]
# 或者: from struct import html [as 别名]
def decode_string(data):
    """Decode string and strip NULL-bytes from end."""
    return data.decode("utf-8").rstrip("\0")


# IRIS Data Types and corresponding python struct format characters
# 4.2 Scalar Definitions, Page 23
# https://docs.python.org/3/library/struct.html#format-characters 
开发者ID:wradlib,项目名称:wradlib,代码行数:10,代码来源:iris.py


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