plastid.util.io.binary module

Tools for reading values from binary files

See Also

struct
Binary data structures in Python
class plastid.util.io.binary.BinaryParserFactory(name, fmt, fields)[source]

Bases: object

Parser factory for different types of binary records.

Creates parsers that unpack binary byte streams into dictionaries that match field names to values. These parsers are most useful as components of binary file readers.

Parameters:
name : str

Name for parser

fmt : str

String specifying binary format of data. See struct

fields : list

Ordered list of field names to bind to data unpacked from binary file

See also

struct
For information on format strings

Examples

A binary RGB color parser:

>>> ColorParser = BinaryParserFactory("ColorParser","3Q",["r","g","b"])
>>> fh = open("some_binary_file_containing_colors.bin","rb") # 'b' is important in mode flag!!
>>> fh.seek(byte_location_of_an_rgb_color)
>>> rgb_dict = ColorParser(fh) # read and parse 3 8-bit integers from file
>>> rgb_dict
    { "r" : 255,
      "g" : 0,
      "b" : 52 }
Attributes:
name : str

Human-readable name for parser

fmt : str

String specifying binary format of data, as specified in struct

fields : list

List of strings specifying variable names to bind to data when unpacked from a binary file, in same order as items in fmt

nt : namedtuple

A namedtuple instance that will provide names to the unpacked data

Methods

__call__(fh[, byte_order]) Parse data from fh into a dictionary mapping field names to their values
calcsize([byte_order]) Return calculated size, in bytes, of record
calcsize(byte_order='<')[source]

Return calculated size, in bytes, of record

Parameters:
byte_order : str

Character indicating endian-ness of data (default: ‘<’ for little-endian)

Returns:
int

Calculated size of record, in bytes

plastid.util.io.binary.find_null_bytes(inp, null='\x00')[source]

Finds all null characters in a byte-formatted input string

Parameters:
inp : bytes (or str in Python 2.7)

byte string

Returns:
:py:class:`numpy.ndarray`

numpy array of integers indexing where the null character ** was found