本文整理匯總了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
示例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)
示例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
示例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)
示例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)
示例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)
示例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
示例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()
示例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
示例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
示例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))
示例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
示例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
示例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
示例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