Struct error python

Функции и исключения модуля struct в Python.

Содержание:

  • Исключение struct.error()
  • Функция struct.pack() [упаковать объект]
  • Функция struct.pack_into() [упаковать и записать в буфер]
  • Функция struct.unpack() [распаковать буфер]
  • Функция struct.unpack_from() [распаковывает буфер начиная с позиции]
  • Функция struct.iter_unpack() [распаковывать буфер в итератор]
  • Функция struct.calcsize() [получить размер структуры]

struct.error(msg):

Исключение struct.error() которое можно поднятое в различных случаях. Аргумент msg — это строка, описывающая, что не так.

>>> import struct
>>> struct.error
# <class 'struct.error'>
>>> struct.error('zdfgzdfg')
# error('zdfgzdfg',)

struct.pack(format, v1, v2, ...):

Функция struct.pack() возвращает объект байтов, содержащий значения v1, v2, …, упакованные в соответствии с форматом format строки формата. Аргументы должны точно соответствовать значениям, требуемым форматом format.

>>> import struct
# данные
>>> data = (150, 'Привет'.encode('utf-8'), 3.14)
# упаковка данных
>>> pack = struct.pack('@ I 12s f', *data)
>>> pack
# b'x96x00x00x00xd0x9fxd1x80xd0xb8xd0xb2xd0xb5xd1x82xc3xf5H@'

struct.pack_into(format, buffer, offset, v1, v2, ...):

Функция struct.pack_into() упаковывает значения v1, v2, … в соответствии с форматом format строки формата и запишет упакованные байты в буфер buffer предназначенный для записи, начиная с позиции offset.

Обратите внимание, что смещение offset является обязательным аргументом.

>>> import struct, ctypes
# данные
>>> data = (150, 'Привет'.encode('utf-8'), 3.14)
# формат данных
>>> fmt = '@ I 12s f'
# размер данных
>>> size = struct.calcsize(fmt)
# создание буфера
>>> buff = ctypes.create_string_buffer(size)
# пакуем данные и пишем в буфер
>>> struct.pack_into(fmt, buff, 0, *data)
>>> buff.raw
# b'x96x00x00x00xd0x9fxd1x80xd0xb8xd0xb2xd0xb5xd1x82xc3xf5H@'

struct.unpack(format, buffer):

Функция struct.unpack() распаковывает буфер buffer, предположительно упакованного функцией struct.pack(format, ...) в соответствии с форматом строки формата.

Результатом работы функции struct.unpack() является кортеж, даже если он содержит ровно один элемент.

Размер буфера в байтах должен соответствовать размеру, требуемому форматом, как отражено в struct.calcsize().

>>> import struct
>>> record = b'raymond   x32x12x08x01x08'
# присвоение c распаковкой
>>> name, serialnum, school, gradelevel = struct.unpack('< 10s H H b', record)
>>> print(name, serialnum, school, gradelevel)
# b'raymond   ' 4658 264 8

struct.unpack_from(format, buffer, offset=0):

Функция struct.unpack_from() распаковывает буфер buffer, начиная с позиции смещения offset, в соответствии с форматом format строки формата.

Результатом работы функции struct.unpack() является кортеж, даже если он содержит ровно один элемент.

Размер буфера в байтах, начиная со смещения позиции, должен быть не меньше размера, требуемого форматом, как отражено в struct.calcsize().

# причитаем и распакуем буфер 'buff', который был 
# создан ранее функцией struct.pack_into() выше.
>>> import struct
# формат данных
>>> fmt = '@ I 12s f'
# читаем буфер 'buff' и распаковываем данные в переменные
>>> a, b, c = s.unpack_from(fmt, buff, 0)
>>> a, b.decode(), c
# (150, 'Привет', 3.140000104904175)

struct.iter_unpack(format, buffer):

Функция struct.iter_unpack() лениво распаковывает буфер buffer в соответствии с форматом строки формата.

Эта функция возвращает итератор, который будет читать куски одинакового размера из буфера, пока все его содержимое не будет использовано. Каждая итерация дает кортеж, как указано в строке формата format.

Размер буфера в байтах должен быть кратным размеру, требуемому форматом, как отражено в struct.calcsize().

struct.calcsize(format):

Функция struct.calcsize() возвращает размер структуры и следовательно байтового объекта, созданного функцией struct.pack(format, ...), соответствующий формату format строки формата.

>>> import struct
# формат данных
>>> fmt = '@ I 12s f'
# размер данных
>>> struct.calcsize(fmt)
# 20

>>> fmt = '120c 12f'
>>> struct.calcsize(fmt)
# 168

This module performs conversions between Python values and C structs represented
as Python bytes objects. This can be used in handling binary data
stored in files or from network connections, among other sources. It uses
Format Strings as compact descriptions of the layout of the C
structs and the intended conversion to/from Python values.

Several struct functions (and methods of Struct) take a buffer
argument. This refers to objects that implement the Buffer Protocol and
provide either a readable or read-writable buffer. The most common types used
for that purpose are bytes and bytearray, but many other types
that can be viewed as an array of bytes implement the buffer protocol, so that
they can be read/filled without additional copying from a bytes object.

7.1.1. Functions and Exceptions¶

The module defines the following exception and functions:

exception struct.error

Exception raised on various occasions; argument is a string describing what
is wrong.

struct.pack(fmt, v1, v2, )

Return a bytes object containing the values v1, v2, … packed according
to the format string fmt. The arguments must match the values required by
the format exactly.

struct.pack_into(fmt, buffer, offset, v1, v2, )

Pack the values v1, v2, … according to the format string fmt and
write the packed bytes into the writable buffer buffer starting at
position offset. Note that offset is a required argument.

struct.unpack(fmt, buffer)

Unpack from the buffer buffer (presumably packed by pack(fmt, ...))
according to the format string fmt. The result is a tuple even if it
contains exactly one item. The buffer’s size in bytes must match the
size required by the format, as reflected by calcsize().

struct.unpack_from(fmt, buffer, offset=0)

Unpack from buffer starting at position offset, according to the format
string fmt. The result is a tuple even if it contains exactly one
item. The buffer’s size in bytes, minus offset, must be at least
the size required by the format, as reflected by calcsize().

struct.iter_unpack(fmt, buffer)

Iteratively unpack from the buffer buffer according to the format
string fmt. This function returns an iterator which will read
equally-sized chunks from the buffer until all its contents have been
consumed. The buffer’s size in bytes must be a multiple of the size
required by the format, as reflected by calcsize().

Each iteration yields a tuple as specified by the format string.

New in version 3.4.

struct.calcsize(fmt)

Return the size of the struct (and hence of the bytes object produced by
pack(fmt, ...)) corresponding to the format string fmt.

7.1.2. Format Strings¶

Format strings are the mechanism used to specify the expected layout when
packing and unpacking data. They are built up from Format Characters,
which specify the type of data being packed/unpacked. In addition, there are
special characters for controlling the Byte Order, Size, and Alignment.

7.1.2.1. Byte Order, Size, and Alignment¶

By default, C types are represented in the machine’s native format and byte
order, and properly aligned by skipping pad bytes if necessary (according to the
rules used by the C compiler).

Alternatively, the first character of the format string can be used to indicate
the byte order, size and alignment of the packed data, according to the
following table:

Character Byte order Size Alignment
@ native native native
= native standard none
< little-endian standard none
> big-endian standard none
! network (= big-endian) standard none

If the first character is not one of these, '@' is assumed.

Native byte order is big-endian or little-endian, depending on the host
system. For example, Intel x86 and AMD64 (x86-64) are little-endian;
Motorola 68000 and PowerPC G5 are big-endian; ARM and Intel Itanium feature
switchable endianness (bi-endian). Use sys.byteorder to check the
endianness of your system.

Native size and alignment are determined using the C compiler’s
sizeof expression. This is always combined with native byte order.

Standard size depends only on the format character; see the table in
the Format Characters section.

Note the difference between '@' and '=': both use native byte order, but
the size and alignment of the latter is standardized.

The form '!' is available for those poor souls who claim they can’t remember
whether network byte order is big-endian or little-endian.

There is no way to indicate non-native byte order (force byte-swapping); use the
appropriate choice of '<' or '>'.

Notes:

  1. Padding is only automatically added between successive structure members.
    No padding is added at the beginning or the end of the encoded struct.
  2. No padding is added when using non-native size and alignment, e.g.
    with ‘<’, ‘>’, ‘=’, and ‘!’.
  3. To align the end of a structure to the alignment requirement of a
    particular type, end the format with the code for that type with a repeat
    count of zero. See Examples.

7.1.2.2. Format Characters¶

Format characters have the following meaning; the conversion between C and
Python values should be obvious given their types. The ‘Standard size’ column
refers to the size of the packed value in bytes when using standard size; that
is, when the format string starts with one of '<', '>', '!' or
'='. When using native size, the size of the packed value is
platform-dependent.

Format C Type Python type Standard size Notes
x pad byte no value    
c char bytes of length 1 1  
b signed char integer 1 (1),(3)
B unsigned char integer 1 (3)
? _Bool bool 1 (1)
h short integer 2 (3)
H unsigned short integer 2 (3)
i int integer 4 (3)
I unsigned int integer 4 (3)
l long integer 4 (3)
L unsigned long integer 4 (3)
q long long integer 8 (2), (3)
Q unsigned long
long
integer 8 (2), (3)
n ssize_t integer   (4)
N size_t integer   (4)
e (7) float 2 (5)
f float float 4 (5)
d double float 8 (5)
s char[] bytes    
p char[] bytes    
P void * integer   (6)

Changed in version 3.3: Added support for the 'n' and 'N' formats.

Changed in version 3.6: Added support for the 'e' format.

Notes:

  1. The '?' conversion code corresponds to the _Bool type defined by
    C99. If this type is not available, it is simulated using a char. In
    standard mode, it is always represented by one byte.

  2. The 'q' and 'Q' conversion codes are available in native mode only if
    the platform C compiler supports C long long, or, on Windows,
    __int64. They are always available in standard modes.

  3. When attempting to pack a non-integer using any of the integer conversion
    codes, if the non-integer has a __index__() method then that method is
    called to convert the argument to an integer before packing.

    Changed in version 3.2: Use of the __index__() method for non-integers is new in 3.2.

  4. The 'n' and 'N' conversion codes are only available for the native
    size (selected as the default or with the '@' byte order character).
    For the standard size, you can use whichever of the other integer formats
    fits your application.

  5. For the 'f', 'd' and 'e' conversion codes, the packed
    representation uses the IEEE 754 binary32, binary64 or binary16 format (for
    'f', 'd' or 'e' respectively), regardless of the floating-point
    format used by the platform.

  6. The 'P' format character is only available for the native byte ordering
    (selected as the default or with the '@' byte order character). The byte
    order character '=' chooses to use little- or big-endian ordering based
    on the host system. The struct module does not interpret this as native
    ordering, so the 'P' format is not available.

  7. The IEEE 754 binary16 “half precision” type was introduced in the 2008
    revision of the IEEE 754 standard. It has a sign
    bit, a 5-bit exponent and 11-bit precision (with 10 bits explicitly stored),
    and can represent numbers between approximately 6.1e-05 and 6.5e+04
    at full precision. This type is not widely supported by C compilers: on a
    typical machine, an unsigned short can be used for storage, but not for math
    operations. See the Wikipedia page on the half-precision floating-point
    format for more information.

A format character may be preceded by an integral repeat count. For example,
the format string '4h' means exactly the same as 'hhhh'.

Whitespace characters between formats are ignored; a count and its format must
not contain whitespace though.

For the 's' format character, the count is interpreted as the length of the
bytes, not a repeat count like for the other format characters; for example,
'10s' means a single 10-byte string, while '10c' means 10 characters.
If a count is not given, it defaults to 1. For packing, the string is
truncated or padded with null bytes as appropriate to make it fit. For
unpacking, the resulting bytes object always has exactly the specified number
of bytes. As a special case, '0s' means a single, empty string (while
'0c' means 0 characters).

When packing a value x using one of the integer formats ('b',
'B', 'h', 'H', 'i', 'I', 'l', 'L',
'q', 'Q'), if x is outside the valid range for that format
then struct.error is raised.

Changed in version 3.1: In 3.0, some of the integer formats wrapped out-of-range values and
raised DeprecationWarning instead of struct.error.

The 'p' format character encodes a “Pascal string”, meaning a short
variable-length string stored in a fixed number of bytes, given by the count.
The first byte stored is the length of the string, or 255, whichever is
smaller. The bytes of the string follow. If the string passed in to
pack() is too long (longer than the count minus 1), only the leading
count-1 bytes of the string are stored. If the string is shorter than
count-1, it is padded with null bytes so that exactly count bytes in all
are used. Note that for unpack(), the 'p' format character consumes
count bytes, but that the string returned can never contain more than 255
bytes.

For the '?' format character, the return value is either True or
False. When packing, the truth value of the argument object is used.
Either 0 or 1 in the native or standard bool representation will be packed, and
any non-zero value will be True when unpacking.

7.1.2.3. Examples¶

Note

All examples assume a native byte order, size, and alignment with a
big-endian machine.

A basic example of packing/unpacking three integers:

>>> from struct import *
>>> pack('hhl', 1, 2, 3)
b'x00x01x00x02x00x00x00x03'
>>> unpack('hhl', b'x00x01x00x02x00x00x00x03')
(1, 2, 3)
>>> calcsize('hhl')
8

Unpacked fields can be named by assigning them to variables or by wrapping
the result in a named tuple:

>>> record = b'raymond   x32x12x08x01x08'
>>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)

>>> from collections import namedtuple
>>> Student = namedtuple('Student', 'name serialnum school gradelevel')
>>> Student._make(unpack('<10sHHb', record))
Student(name=b'raymond   ', serialnum=4658, school=264, gradelevel=8)

The ordering of format characters may have an impact on size since the padding
needed to satisfy alignment requirements is different:

>>> pack('ci', b'*', 0x12131415)
b'*x00x00x00x12x13x14x15'
>>> pack('ic', 0x12131415, b'*')
b'x12x13x14x15*'
>>> calcsize('ci')
8
>>> calcsize('ic')
5

The following format 'llh0l' specifies two pad bytes at the end, assuming
longs are aligned on 4-byte boundaries:

>>> pack('llh0l', 1, 2, 3)
b'x00x00x00x01x00x00x00x02x00x03x00x00'

This only works when native size and alignment are in effect; standard size and
alignment does not enforce any alignment.

See also

Module array
Packed binary storage of homogeneous data.
Module xdrlib
Packing and unpacking of XDR data.

7.1.3. Classes¶

The struct module also defines the following type:

class struct.Struct(format)

Return a new Struct object which writes and reads binary data according to
the format string format. Creating a Struct object once and calling its
methods is more efficient than calling the struct functions with the
same format since the format string only needs to be compiled once.

Compiled Struct objects support the following methods and attributes:

pack(v1, v2, )

Identical to the pack() function, using the compiled format.
(len(result) will equal size.)

pack_into(buffer, offset, v1, v2, )

Identical to the pack_into() function, using the compiled format.

unpack(buffer)

Identical to the unpack() function, using the compiled format.
The buffer’s size in bytes must equal size.

unpack_from(buffer, offset=0)

Identical to the unpack_from() function, using the compiled format.
The buffer’s size in bytes, minus offset, must be at least
size.

iter_unpack(buffer)

Identical to the iter_unpack() function, using the compiled format.
The buffer’s size in bytes must be a multiple of size.

New in version 3.4.

format

The format string used to construct this Struct object.

size

The calculated size of the struct (and hence of the bytes object produced
by the pack() method) corresponding to format.

The Python struct module is used to provide a simple Pythonic interface to access and manipulate C’s structure datatype. This can be a handy tool if you ever need to deal with C code and don’t have the time to write tools in C since it is a low-level language.

This module can convert Python values to a C structure and vice-versa. The C structure is used as a Python bytes object since there is nothing called an object in C; only byte-sized data structures.

Let’s understand how we can use this module to have a Python interface to C structures.


Python struct Module Methods

In this module, since we are concerned with C structures, let’s look at some of the functions that this module provides us with.

struct.pack()

This is used to pack elements into a Python byte-string (byte object). Since the mode of storage is based on bytes, C based programs can use the output of pack(), from a Python program.

Format: struct.pack(format, v1, v2, …)

v1, v2, … are the values which will be packed into the byte object. They represent the field values for the C structure. Since a C structure having n fields must exactly have n values, the arguments must match the values required by the format exactly.

Here, format refers to the format of the packing. This is needed since we need to specify the datatype of the byte-string, as it is used with C code. The below table lists the most common values for format. We need one format per value to specify it’s datatype.

Format C Datatype Python type
c char a string of length 1
? _Bool bool
h short integer
l long integer
i int integer
f float float
d double float
s char[] string

Let’s understand this using some examples.

The below snippet stores the 3 integers 1, 2 and 3 in a byte object using pack(). Since the size of an integer is 4 bytes on my machine, you see 3 blocks of 4 bytes, which correspond to 3 integers in C.

import struct

# We pack 3 integers, so 'iii' is required
variable = struct.pack('iii', 1, 2, 3)
print(type(variable), variable)

variable_2 = struct.pack('iic', 1, 2, b'A')
print('n', variable_2)

Output

<class 'bytes'> b'x01x00x00x00x02x00x00x00x03x00x00x00'
b'x01x00x00x00x02x00x00x00A'

If the appropriate type is not passed, the exception struct.error will be raised by the Python struct module.

import struct

# Error!! Incorrect datatype assignment
variable = struct.pack('ccc', 1, 2, 3)
print(type(variable), variable)

Output

struct.error: char format requires a bytes object of length 1

struct.unpack()

This function of the Python struct module, unpacks the packed value into its original representation according to an appropriate format. This returns a tuple of size equal to the number of values passed since the byte object is unpacked to give the elements.

Format: struct.unpack(format, string)

This unpacks the byte string according to the format format specifier.

This is the reverse of struct.pack(). Let’s take one of the old byte strings that we produced using that and try to get back the python values passed to it using unpack().

import struct

byte_str = b'x01x00x00x00x02x00x00x00A'

# Using the same format specifier as before, since
# we want to get Python values for the same byte-string
tuple_vals = struct.unpack('iic', byte_str)
print(tuple_vals)

Output

As you can see, indeed, we can get pack our old Python values from this tuple, provided we use the same format specifier for both pack() and unpack().


struct.calcsize()

This function returns the total size of the String representation of the struct using a given format specifier, to retrieve the types of the data and calculate the size.

Format: struct.calcsize(fmt)

import struct

print('C Integer Size in Bytes:', struct.calcsize('i'))
print('Size of 3 characters in Bytes:', struct.calcsize('ccc'))

Output

C Integer Size in Bytes: 4
Size of 3 characters in Bytes: 3

struct.pack_into()

This function is used pack values into a Python string buffer, available in the ctypes module.

Format: struct.pack_into(fmt, buffer, offset, v1, v2, …)

Here, fmt refers to the format specifier, as always. buffer is the string buffer which will now contain the packed values, specified. You can also specify an offset location from the base address from which packing will occur.

This does not return any value, and simply stores the values into the buffer string.

import struct 
import ctypes 

# We will create a string buffer having a size
# equal to that of a struct with 'iic' values.
buf_size = struct.calcsize('iic') 

# Create the string buffer
buff = ctypes.create_string_buffer(buf_size) 
  
# struct.pack() returns the packed data 
struct.pack_into('iic', buff, 0, 1, 2, b'A')

print(buff)

# Display the contents of the buffer
print(buff[:])

Output

<ctypes.c_char_Array_9 object at 0x7f4bccef1040>
b'x01x00x00x00x02x00x00x00A'

Indeed, we get our packed values in the buffer string.


struct.unpack_from()

Similar to unpack(), a counterpart exists for unpacking values from a buffer string. This does the reverse of struct.pack_into().

Format: struct.unpack_from(fmt, buffer, offset)

This will return a tuple of values, similar to struct.unpack().

import struct 
import ctypes 

# We will create a string buffer having a size
# equal to that of a struct with 'iic' values.
buf_size = struct.calcsize('iic') 

# Create the string buffer
buff = ctypes.create_string_buffer(buf_size) 
  
# struct.pack() returns the packed data 
struct.pack_into('iic', buff, 0, 1, 2, b'A')

print(struct.unpack_from('iic', buff, 0))

Output


Conclusion

In this article, we learned about using Python struct module to deal with C-type structure objects.

References

  • JournalDev article on Python struct module

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    This module performs conversions between Python values and C structs represented as Python bytes objects. Format strings are the mechanism used to specify the expected layout when packing and unpacking data. Module struct is available in Python 3.x and not on 2.x, thus these codes will run on Python3 interpreter.

    Struct Functions

    • struct.pack()
      Syntax: 
      struct.pack(format, v1, v2, ...)

      Return a string containing the values v1, v2, … , that are packed according to the given format (Format strings are the mechanism used to specify the expected layout when packing and unpacking data).The values followed by the format must be as per the format only, else struct.error is raised.

      import struct

      var = struct.pack('hhl',1,2,3)

      print(var)

      var = struct.pack('iii',1,2,3)

      print(var)

      Output:

      b'x01x00x02x00x00x00x00x00x03x00x00x00x00x00x00x00'
      b'x01x00x00x00x02x00x00x00x03x00x00x00'
      
    • struct.unpack()
      Syntax:
      struct.unpack(fmt, string)

      Return the values v1, v2, … , that are unpacked according to the given format(1st argument). Values returned by this function are returned as tuples of size that is equal to the number of values passed through struct.pack() during packing.

      import struct

      var = struct.pack('?hil', True, 2, 5, 445)

      print(var)

      tup = struct.unpack('?hil', var)

      print(tup)

      var = struct.pack('qf', 5, 2.3)

      print(var)

      tup = struct.unpack('qf', var)

      print(tup)

      Output:

      b'x01x00x02x00x05x00x00x00xbdx01x00x00x00x00x00x00'
      (True, 2, 5, 445)
      b'x05x00x00x00x00x00x00x0033x13@'
      (5, 2.299999952316284)
      

      Note: ‘b’ in the Output stands for binary.

    • struct.calcsize()
      Syntax:
      struct.calcsize(fmt)
      fmt: format 

      Return the size of the struct (and hence of the string) corresponding to the given format. calcsize() is important function, and is required for function such as struct.pack_into() and struct.unpack_from(), which require offset value and buffer as well.

      import struct

      var = struct.pack('?hil', True, 2, 5, 445)

      print(var)

      print(struct.calcsize('?hil'))

      print(struct.calcsize('qf'))

      Output:

      b'x01x00x02x00x05x00x00x00xbdx01x00x00x00x00x00x00'
      16
      12
      

      import struct

      var = struct.pack('bi', 56, 0x12131415)

      print(var)

      print(struct.calcsize('bi'))

      var = struct.pack('ib', 0x12131415, 56)

      print(var)

      print(struct.calcsize('ib'))

      Output:

      b'8x00x00x00x15x14x13x12'
      8
      b'x15x14x13x128'
      5
      

      Note: The ordering of format characters may have an impact on size.

    • Exception struct.error
      Exception struct.error describes what is wrong at passing arguments, when a wrong argument is passed struct.error is raised.

      from struct import error

      print(error)

      Note: This is piece of code is not useful, anywhere other than exception handling, and is used to show that ‘error’ upon interpreted shows about the class.

    • struct.pack_into()
      Syntax:
      struct.pack_into(fmt, buffer, offset, v1, v2, ...)
      fmt: data type format
      buffer: writable buffer which starts at offset (optional)
      v1,v2.. : values 
    • struct.unpack_from()
      Syntax:
      struct.unpack_from(fmt, buffer[,offset = 0])fmt: data type format
      buffer: writable buffer which starts at offset (optional)

      Returns a tuple, similar to struct.unpack()

      import struct

      import ctypes

      siz = struct.calcsize('hhl')

      print(siz)

      buff = ctypes.create_string_buffer(siz)

      x = struct.pack('hhl', 2, 2, 3)

      print(x)

      print(struct.unpack('hhl', x))

      struct.pack_into('hhl', buff, 0, 2, 2, 3)

      print(struct.unpack_from('hhl', buff, 0))

      Output:

      16
      b'x02x00x02x00x00x00x00x00x03x00x00x00x00x00x00x00'
      (2, 2, 3)
      (2, 2, 3)
      

    Reference https://docs.python.org/2/library/struct.html
    This article is contributed by Piyush Doorwar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

    Исходный код: Lib/struct.py.


    Этот модуль выполняет преобразования между значениями Python и структурами C, представленными в виде объектов Python bytes. Это может быть использовано при работе с двоичными данными, хранящимися в файлах или из сетевых соединений, среди прочих источников. Он использует Строки формата в качестве компактных описаний расположения C-структур и предполагаемого преобразования в/из значений Python.

    Примечание

    По умолчанию результат упаковки данной C-структуры включает байты-заглушки, чтобы сохранить правильное выравнивание для соответствующих C-типов; аналогично, выравнивание учитывается при распаковке. Такое поведение выбрано для того, чтобы байты упакованной структуры точно соответствовали расположению в памяти соответствующей C-структуры. Чтобы работать с платформонезависимыми форматами данных или опустить неявные байты вставки, используйте standard размер и выравнивание вместо native размер и выравнивание: подробности см. в Порядок, размер и выравнивание байтов.

    Некоторые функции struct (и методы Struct) принимают аргумент буфер. Это относится к объектам, реализующим Буферный протокол и предоставляющим буфер для чтения или записи. Наиболее часто для этой цели используются типы bytes и bytearray, но многие другие типы, которые можно рассматривать как массив байтов, реализуют протокол буфера, так что они могут быть прочитаны/заполнены без дополнительного копирования из объекта bytes.

    Функции и исключения¶

    Модуль определяет следующие исключения и функции:

    exception struct.error

    Исключение, возникающее в различных случаях; аргумент — строка, описывающая ошибку.

    struct.pack(format, v1, v2, )

    Возвращает объект bytes, содержащий значения v1, v2, …, упакованные в соответствии со строкой формата format. Аргументы должны точно соответствовать значениям, требуемым форматом.

    struct.pack_into(format, buffer, offset, v1, v2, )

    Упакуйте значения v1, v2, … в соответствии со строкой формата format и запишите упакованные байты в записываемый буфер buffer, начиная с позиции offset. Обратите внимание, что offset является обязательным аргументом.

    struct.unpack(format, buffer)

    Распаковать из буфера buffer (предположительно упакованного командой pack(format, ...)) в соответствии со строкой формата format. Результатом является кортеж, даже если он содержит ровно один элемент. Размер буфера в байтах должен соответствовать размеру, требуемому форматом, что отражено в calcsize().

    struct.unpack_from(format, /, buffer, offset=0)

    Распаковать из буфера, начиная с позиции offset, в соответствии со строкой формата format. Результатом является кортеж, даже если он содержит ровно один элемент. Размер буфера в байтах, начиная с позиции offset, должен быть не меньше размера, требуемого форматом, что отражено в строке calcsize().

    struct.iter_unpack(format, buffer)

    Итеративно распаковать из буфера buffer в соответствии со строкой формата format. Эта функция возвращает итератор, который будет считывать из буфера одинаковые по размеру фрагменты, пока не будет израсходовано все его содержимое. Размер буфера в байтах должен быть кратен размеру, требуемому форматом, что отражается в calcsize().

    Каждая итерация дает кортеж, заданный строкой формата.

    Добавлено в версии 3.4.

    struct.calcsize(format)

    Возвращает размер структуры (и, следовательно, байтового объекта, создаваемого командой pack(format, ...)), соответствующей строке формата format.

    Строки формата¶

    Строки формата — это механизм, используемый для указания ожидаемого расположения при упаковке и распаковке данных. Они строятся из Символы формата, которые определяют тип упаковываемых/распаковываемых данных. Кроме того, существуют специальные символы для управления Порядок, размер и выравнивание байтов.

    Порядок, размер и выравнивание байтов¶

    По умолчанию типы C представлены в родном формате машины и порядке байтов, а также правильно выровнены, при необходимости пропуская байты-заглушки (в соответствии с правилами, используемыми компилятором C).

    В качестве альтернативы, первый символ строки формата может использоваться для указания порядка байтов, размера и выравнивания упакованных данных, в соответствии со следующей таблицей:

    Персонаж

    Порядок байтов

    Размер

    Выравнивание

    @

    родной

    родной

    родной

    =

    родной

    стандарт

    нет

    <

    little-endian

    стандарт

    нет

    >

    big-endian

    стандарт

    нет

    !

    сеть (= big-endian)

    стандарт

    нет

    Если первый символ не является одним из них, предполагается '@'.

    Родной порядок байтов — big-endian или little-endian, в зависимости от хост-системы. Например, Intel x86 и AMD64 (x86-64) — little-endian; IBM z и большинство старых архитектур — big-endian; ARM, RISC-V и IBM Power имеют переключаемый порядок (bi-endian, хотя первые два почти всегда little-endian на практике). Используйте sys.byteorder, чтобы проверить конечность вашей системы.

    Родной размер и выравнивание определяются с помощью выражения sizeof компилятора Си. Оно всегда сочетается с родным порядком байтов.

    Стандартный размер зависит только от символа формата; см. таблицу в разделе Символы формата.

    Обратите внимание на разницу между '@' и '=': оба используют родной порядок байтов, но размер и выравнивание последнего стандартизированы.

    Форма '!' представляет порядок байтов в сети, который всегда является big-endian, как определено в IETF RFC 1700.

    Не существует способа указать неродной порядок байтов (принудительная замена байтов); используйте соответствующий выбор '<' или '>'.

    Примечания:

    1. Вставка автоматически добавляется только между последовательными членами структуры. В начале и в конце закодированной структуры добавление вставки не производится.

    2. При использовании неродного размера и выравнивания, например, при использовании „<“, „>“, „=“ и „!“, вставка не добавляется.

    3. Чтобы выровнять конец структуры в соответствии с требованием выравнивания определенного типа, завершите формат кодом для этого типа с количеством повторений, равным нулю. См. Примеры.

    Символы формата¶

    Символы формата имеют следующее значение; преобразование между значениями C и Python должно быть очевидным, учитывая их типы. Колонка „Standard size“ означает размер упакованного значения в байтах при использовании стандартного размера; то есть, когда строка формата начинается с одного из '<', '>', '!' или '='. При использовании собственного размера размер упакованного значения зависит от платформы.

    Формат

    C Тип

    Тип Python

    Стандартный размер

    Примечания

    x

    байт блокнота

    нет значения

    c

    char

    байт длины 1

    1

    b

    signed char

    целое число

    1

    (1), (2)

    B

    unsigned char

    целое число

    1

    (2)

    ?

    _Bool

    bool

    1

    (1)

    h

    short

    целое число

    2

    (2)

    H

    unsigned short

    целое число

    2

    (2)

    i

    int

    целое число

    4

    (2)

    I

    unsigned int

    целое число

    4

    (2)

    l

    long

    целое число

    4

    (2)

    L

    unsigned long

    целое число

    4

    (2)

    q

    long long

    целое число

    8

    (2)

    Q

    unsigned long long

    целое число

    8

    (2)

    n

    ssize_t

    целое число

    (3)

    N

    size_t

    целое число

    (3)

    e

    (6)

    float

    2

    (4)

    f

    float

    float

    4

    (4)

    d

    double

    float

    8

    (4)

    s

    char[]

    байты

    p

    char[]

    байты

    P

    void*

    целое число

    (5)

    Изменено в версии 3.3: Добавлена поддержка форматов 'n' и 'N'.

    Изменено в версии 3.6: Добавлена поддержка формата 'e'.

    Примечания:

    1. Код преобразования '?' соответствует типу _Bool, определенному в C99. Если этот тип недоступен, он моделируется с помощью char. В стандартном режиме он всегда представлен одним байтом.

    2. При попытке упаковать нецелое число с помощью любого из кодов преобразования целых чисел, если нецелое число имеет метод __index__(), то этот метод вызывается для преобразования аргумента в целое число перед упаковкой.

      Изменено в версии 3.2: Добавлено использование метода __index__() для нецелых чисел.

    3. Коды преобразования 'n' и 'N' доступны только для собственного размера (выбранного по умолчанию или с помощью символа порядка байтов '@'). Для стандартного размера вы можете использовать любой другой целочисленный формат, подходящий для вашего приложения.

    4. Для кодов преобразования 'f', 'd' и 'e' упакованное представление использует формат IEEE 754 binary32, binary64 или binary16 (для 'f', 'd' или 'e' соответственно), независимо от формата плавающей точки, используемого платформой.

    5. Символ формата 'P' доступен только для собственного упорядочения байтов (выбранного по умолчанию или с помощью символа порядка байтов '@'). Символ порядка байтов '=' выбирает использование little- или big-endian упорядочивания в зависимости от хост-системы. Модуль struct не интерпретирует это как собственное упорядочивание, поэтому формат 'P' недоступен.

    6. Тип IEEE 754 binary16 «половинной точности» был введен в ревизии 2008 года IEEE 754 standard. Он имеет знаковый бит, 5-битную экспоненту и 11-битную точность (с явным сохранением 10 бит), и может представлять числа между приблизительно 6.1e-05 и 6.5e+04 с полной точностью. Этот тип не очень широко поддерживается компиляторами языка Си: на типичной машине беззнаковое сокращение может использоваться для хранения, но не для математических операций. Дополнительную информацию см. на странице Википедии, посвященной half-precision floating-point format.

    Символу формата может предшествовать интегральный счетчик повторов. Например, форматная строка '4h' означает то же самое, что и 'hhhh'.

    Символы пробелов между форматами игнорируются; однако счетчик и его формат не должны содержать пробелов.

    Для символа формата 's' счетчик интерпретируется как длина байта, а не как счетчик повторений, как для других символов формата; например, '10s' означает одну 10-байтовую строку, а '10c' — 10 символов. Если счетчик не указан, то по умолчанию он равен 1. При упаковке строка усекается или заполняется нулевыми байтами, чтобы она поместилась. При распаковке результирующий объект bytes всегда имеет точно указанное количество байт. Как частный случай, '0s' означает единственную пустую строку (в то время как '0c' означает 0 символов).

    При упаковке значения x с использованием одного из целочисленных форматов ('b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q'), если x находится вне допустимого диапазона для данного формата, то возникает ошибка struct.error.

    Изменено в версии 3.1: Ранее некоторые целочисленные форматы заворачивали значения, выходящие за пределы диапазона, и выдавали DeprecationWarning вместо struct.error.

    Символ формата 'p' кодирует «строку Паскаля», то есть короткую строку переменной длины, хранящуюся в фиксированном количестве байт, задаваемом счетчиком. Первый сохраненный байт — это длина строки или 255, в зависимости от того, что меньше. Далее следуют байты строки. Если строка, переданная в pack(), слишком длинная (длиннее, чем счетчик минус 1), сохраняются только первые байты строки count-1. Если строка короче, чем count-1, она заполняется нулевыми байтами, так что всего используется ровно счетное количество байт. Обратите внимание, что для unpack(), символ формата 'p' потребляет count байт, но возвращаемая строка никогда не может содержать более 255 байт.

    Для символа формата '?' возвращаемым значением является либо True, либо False. При упаковке используется истинностное значение объекта аргумента. Упаковывается либо 0, либо 1 в собственном или стандартном представлении bool, а при распаковке любое ненулевое значение будет True.

    Примеры¶

    Примечание

    Все примеры предполагают собственный порядок байтов, размер и выравнивание на машине с big-endian.

    Базовый пример упаковки/распаковки трех целых чисел:

    >>> from struct import *
    >>> pack('hhl', 1, 2, 3)
    b'x00x01x00x02x00x00x00x03'
    >>> unpack('hhl', b'x00x01x00x02x00x00x00x03')
    (1, 2, 3)
    >>> calcsize('hhl')
    8
    

    Распакованные поля можно назвать, присвоив их переменным или обернув результат в именованный кортеж:

    >>> record = b'raymond   x32x12x08x01x08'
    >>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)
    
    >>> from collections import namedtuple
    >>> Student = namedtuple('Student', 'name serialnum school gradelevel')
    >>> Student._make(unpack('<10sHHb', record))
    Student(name=b'raymond   ', serialnum=4658, school=264, gradelevel=8)
    

    Порядок следования символов формата может влиять на размер, так как вставка, необходимая для удовлетворения требований выравнивания, различна:

    >>> pack('ci', b'*', 0x12131415)
    b'*x00x00x00x12x13x14x15'
    >>> pack('ic', 0x12131415, b'*')
    b'x12x13x14x15*'
    >>> calcsize('ci')
    8
    >>> calcsize('ic')
    5
    

    Следующий формат 'llh0l' задает два байта прокладки в конце, предполагая, что длинные строки выровнены по 4-байтовым границам:

    >>> pack('llh0l', 1, 2, 3)
    b'x00x00x00x01x00x00x00x02x00x03x00x00'
    

    Это работает только тогда, когда действуют собственные размеры и выравнивание; стандартные размеры и выравнивание не обеспечивают никакого выравнивания.

    См.также

    Модуль array

    Упакованное двоичное хранение однородных данных.

    Модуль xdrlib

    Упаковка и распаковка данных XDR.

    Занятия¶

    Модуль struct также определяет следующий тип:

    class struct.Struct(format)

    Возвращает новый объект Struct, который записывает и читает двоичные данные в соответствии со строкой формата format. Создание объекта Struct один раз и вызов его методов более эффективно, чем вызов функций struct с тем же форматом, поскольку строку формата нужно скомпилировать только один раз.

    Примечание

    Скомпилированные версии последних строк формата, переданных в Struct и функции уровня модуля, кэшируются, поэтому программам, использующим только несколько строк формата, не нужно беспокоиться о повторном использовании одного экземпляра Struct.

    Скомпилированные объекты Struct поддерживают следующие методы и атрибуты:

    pack(v1, v2, )

    Идентична функции pack(), использует скомпилированный формат. (len(result) будет равно size).

    pack_into(buffer, offset, v1, v2, )

    Идентична функции pack_into(), использует скомпилированный формат.

    unpack(buffer)

    Идентична функции unpack(), использует скомпилированный формат. Размер буфера в байтах должен быть равен size.

    unpack_from(buffer, offset=0)

    Идентична функции unpack_from(), использует скомпилированный формат. Размер буфера в байтах, начиная с позиции offset, должен быть не менее size.

    iter_unpack(buffer)

    Идентична функции iter_unpack(), использует скомпилированный формат. Размер буфера в байтах должен быть кратен size.

    Добавлено в версии 3.4.

    format

    Строка формата, используемая для построения данного объекта Struct.

    Изменено в версии 3.7: Тип форматной строки теперь str вместо bytes.

    size

    Вычисленный размер struct (и, следовательно, байтового объекта, создаваемого методом pack()), соответствующего format.

    struct — Interpret bytes as packed binary data

    Source code: Lib/struct.py

    This module performs conversions between Python values and C structs represented as Python bytes objects. This can be used in handling binary data stored in files or from network connections, among other sources. It uses Format Strings as compact descriptions of the layout of the C structs and the intended conversion to/from Python values.

    Note

    By default, the result of packing a given C struct includes pad bytes in order to maintain proper alignment for the C types involved; similarly, alignment is taken into account when unpacking. This behavior is chosen so that the bytes of a packed struct correspond exactly to the layout in memory of the corresponding C struct. To handle platform-independent data formats or omit implicit pad bytes, use standard size and alignment instead of native size and alignment: see Byte Order, Size, and Alignment for details.

    Several struct functions (and methods of Struct) take a buffer argument. This refers to objects that implement the Buffer Protocol and provide either a readable or read-writable buffer. The most common types used for that purpose are bytes and bytearray, but many other types that can be viewed as an array of bytes implement the buffer protocol, so that they can be read/filled without additional copying from a bytes object.

    Functions and Exceptions

    The module defines the following exception and functions:

    exception struct.error

    Exception raised on various occasions; argument is a string describing what is wrong.

    struct.pack(format, v1, v2, ...)

    Return a bytes object containing the values v1, v2, … packed according to the format string format. The arguments must match the values required by the format exactly.

    struct.pack_into(format, buffer, offset, v1, v2, ...)

    Pack the values v1, v2, … according to the format string format and write the packed bytes into the writable buffer buffer starting at position offset. Note that offset is a required argument.

    struct.unpack(format, buffer)

    Unpack from the buffer buffer (presumably packed by pack(format, ...)) according to the format string format. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes must match the size required by the format, as reflected by calcsize().

    struct.unpack_from(format, /, buffer, offset=0)

    Unpack from buffer starting at position offset, according to the format string format. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes, starting at position offset, must be at least the size required by the format, as reflected by calcsize().

    struct.iter_unpack(format, buffer)

    Iteratively unpack from the buffer buffer according to the format string format. This function returns an iterator which will read equally-sized chunks from the buffer until all its contents have been consumed. The buffer’s size in bytes must be a multiple of the size required by the format, as reflected by calcsize().

    Each iteration yields a tuple as specified by the format string.

    New in version 3.4.

    struct.calcsize(format)

    Return the size of the struct (and hence of the bytes object produced by pack(format, ...)) corresponding to the format string format.

    Format Strings

    Format strings are the mechanism used to specify the expected layout when packing and unpacking data. They are built up from Format Characters, which specify the type of data being packed/unpacked. In addition, there are special characters for controlling the Byte Order, Size, and Alignment.

    Byte Order, Size, and Alignment

    By default, C types are represented in the machine’s native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler).

    Alternatively, the first character of the format string can be used to indicate the byte order, size and alignment of the packed data, according to the following table:

    Character

    Byte order

    Size

    Alignment

    @

    native

    native

    native

    =

    native

    standard

    none

    <

    little-endian

    standard

    none

    >

    big-endian

    standard

    none

    !

    network (= big-endian)

    standard

    none

    If the first character is not one of these, '@' is assumed.

    Native byte order is big-endian or little-endian, depending on the host system. For example, Intel x86 and AMD64 (x86-64) are little-endian; Motorola 68000 and PowerPC G5 are big-endian; ARM and Intel Itanium feature switchable endianness (bi-endian). Use sys.byteorder to check the endianness of your system.

    Native size and alignment are determined using the C compiler’s sizeof expression. This is always combined with native byte order.

    Standard size depends only on the format character; see the table in the Format Characters section.

    Note the difference between '@' and '=': both use native byte order, but the size and alignment of the latter is standardized.

    The form '!' represents the network byte order which is always big-endian as defined in IETF RFC 1700.

    There is no way to indicate non-native byte order (force byte-swapping); use the appropriate choice of '<' or '>'.

    Notes:

    1. Padding is only automatically added between successive structure members. No padding is added at the beginning or the end of the encoded struct.
    2. No padding is added when using non-native size and alignment, e.g. with ‘<’, ‘>’, ‘=’, and ‘!’.
    3. To align the end of a structure to the alignment requirement of a particular type, end the format with the code for that type with a repeat count of zero. See Examples.

    Format Characters

    Format characters have the following meaning; the conversion between C and Python values should be obvious given their types. The ‘Standard size’ column refers to the size of the packed value in bytes when using standard size; that is, when the format string starts with one of '<', '>', '!' or '='. When using native size, the size of the packed value is platform-dependent.

    Format

    C Type

    Python type

    Standard size

    Notes

    x

    pad byte

    no value

    c

    char

    bytes of length 1

    1

    b

    signed char

    integer

    1

    (1), (2)

    B

    unsigned char

    integer

    1

    (2)

    ?

    _Bool

    bool

    1

    (1)

    h

    short

    integer

    2

    (2)

    H

    unsigned short

    integer

    2

    (2)

    i

    int

    integer

    4

    (2)

    I

    unsigned int

    integer

    4

    (2)

    l

    long

    integer

    4

    (2)

    L

    unsigned long

    integer

    4

    (2)

    q

    long long

    integer

    8

    (2)

    Q

    unsigned long
    long

    integer

    8

    (2)

    n

    ssize_t

    integer

    (3)

    N

    size_t

    integer

    (3)

    e

    (6)

    float

    2

    (4)

    f

    float

    float

    4

    (4)

    d

    double

    float

    8

    (4)

    s

    char[]

    bytes

    p

    char[]

    bytes

    P

    void *

    integer

    (5)

    Changed in version 3.3: Added support for the 'n' and 'N' formats.

    Changed in version 3.6: Added support for the 'e' format.

    Notes:

    1. The '?' conversion code corresponds to the _Bool type defined by C99. If this type is not available, it is simulated using a char. In standard mode, it is always represented by one byte.
    2. When attempting to pack a non-integer using any of the integer conversion codes, if the non-integer has a __index__() method then that method is called to convert the argument to an integer before packing.

      Changed in version 3.2: Added use of the __index__() method for non-integers.

    3. The 'n' and 'N' conversion codes are only available for the native size (selected as the default or with the '@' byte order character). For the standard size, you can use whichever of the other integer formats fits your application.
    4. For the 'f', 'd' and 'e' conversion codes, the packed representation uses the IEEE 754 binary32, binary64 or binary16 format (for 'f', 'd' or 'e' respectively), regardless of the floating-point format used by the platform.
    5. The 'P' format character is only available for the native byte ordering (selected as the default or with the '@' byte order character). The byte order character '=' chooses to use little- or big-endian ordering based on the host system. The struct module does not interpret this as native ordering, so the 'P' format is not available.
    6. The IEEE 754 binary16 “half precision” type was introduced in the 2008 revision of the IEEE 754 standard. It has a sign bit, a 5-bit exponent and 11-bit precision (with 10 bits explicitly stored), and can represent numbers between approximately 6.1e-05 and 6.5e+04 at full precision. This type is not widely supported by C compilers: on a typical machine, an unsigned short can be used for storage, but not for math operations. See the Wikipedia page on the half-precision floating-point format for more information.

    A format character may be preceded by an integral repeat count. For example, the format string '4h' means exactly the same as 'hhhh'.

    Whitespace characters between formats are ignored; a count and its format must not contain whitespace though.

    For the 's' format character, the count is interpreted as the length of the bytes, not a repeat count like for the other format characters; for example, '10s' means a single 10-byte string, while '10c' means 10 characters. If a count is not given, it defaults to 1. For packing, the string is truncated or padded with null bytes as appropriate to make it fit. For unpacking, the resulting bytes object always has exactly the specified number of bytes. As a special case, '0s' means a single, empty string (while '0c' means 0 characters).

    When packing a value x using one of the integer formats ('b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q'), if x is outside the valid range for that format then struct.error is raised.

    Changed in version 3.1: Previously, some of the integer formats wrapped out-of-range values and raised DeprecationWarning instead of struct.error.

    The 'p' format character encodes a “Pascal string”, meaning a short variable-length string stored in a fixed number of bytes, given by the count. The first byte stored is the length of the string, or 255, whichever is smaller. The bytes of the string follow. If the string passed in to pack() is too long (longer than the count minus 1), only the leading count-1 bytes of the string are stored. If the string is shorter than count-1, it is padded with null bytes so that exactly count bytes in all are used. Note that for unpack(), the 'p' format character consumes count bytes, but that the string returned can never contain more than 255 bytes.

    For the '?' format character, the return value is either True or False. When packing, the truth value of the argument object is used. Either 0 or 1 in the native or standard bool representation will be packed, and any non-zero value will be True when unpacking.

    Examples

    Note

    All examples assume a native byte order, size, and alignment with a big-endian machine.

    A basic example of packing/unpacking three integers:

    >>> from struct import *
    >>> pack('hhl', 1, 2, 3)
    b'x00x01x00x02x00x00x00x03'
    >>> unpack('hhl', b'x00x01x00x02x00x00x00x03')
    (1, 2, 3)
    >>> calcsize('hhl')
    8
    

    Unpacked fields can be named by assigning them to variables or by wrapping the result in a named tuple:

    >>> record = b'raymond   x32x12x08x01x08'
    >>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)
    
    >>> from collections import namedtuple
    >>> Student = namedtuple('Student', 'name serialnum school gradelevel')
    >>> Student._make(unpack('<10sHHb', record))
    Student(name=b'raymond   ', serialnum=4658, school=264, gradelevel=8)
    

    The ordering of format characters may have an impact on size since the padding needed to satisfy alignment requirements is different:

    >>> pack('ci', b'*', 0x12131415)
    b'*x00x00x00x12x13x14x15'
    >>> pack('ic', 0x12131415, b'*')
    b'x12x13x14x15*'
    >>> calcsize('ci')
    8
    >>> calcsize('ic')
    5
    

    The following format 'llh0l' specifies two pad bytes at the end, assuming longs are aligned on 4-byte boundaries:

    >>> pack('llh0l', 1, 2, 3)
    b'x00x00x00x01x00x00x00x02x00x03x00x00'
    

    This only works when native size and alignment are in effect; standard size and alignment does not enforce any alignment.

    See also

    Module array

    Packed binary storage of homogeneous data.

    Module xdrlib

    Packing and unpacking of XDR data.

    Classes

    The struct module also defines the following type:

    class struct.Struct(format)

    Return a new Struct object which writes and reads binary data according to the format string format. Creating a Struct object once and calling its methods is more efficient than calling the struct functions with the same format since the format string only needs to be compiled once.

    Note

    The compiled versions of the most recent format strings passed to Struct and the module-level functions are cached, so programs that use only a few format strings needn’t worry about reusing a single Struct instance.

    Compiled Struct objects support the following methods and attributes:

    pack(v1, v2, ...)

    Identical to the pack() function, using the compiled format. (len(result) will equal size.)

    pack_into(buffer, offset, v1, v2, ...)

    Identical to the pack_into() function, using the compiled format.

    unpack(buffer)

    Identical to the unpack() function, using the compiled format. The buffer’s size in bytes must equal size.

    unpack_from(buffer, offset=0)

    Identical to the unpack_from() function, using the compiled format. The buffer’s size in bytes, starting at position offset, must be at least size.

    iter_unpack(buffer)

    Identical to the iter_unpack() function, using the compiled format. The buffer’s size in bytes must be a multiple of size.

    New in version 3.4.

    format

    The format string used to construct this Struct object.

    Changed in version 3.7: The format string type is now str instead of bytes.

    size

    The calculated size of the struct (and hence of the bytes object produced by the pack() method) corresponding to format.

    Понравилась статья? Поделить с друзьями:
  • Struct error i format requires 2147483648 number 2147483647
  • Struct error argument out of range
  • Strtrail txt ошибка виндовс 10
  • Strtrail txt ошибка windows 10 как исправить
  • Stronghold ошибка 0xc0000022 windows 10