本文整理汇总了Python中struct.Struct.pack方法的典型用法代码示例。如果您正苦于以下问题:Python Struct.pack方法的具体用法?Python Struct.pack怎么用?Python Struct.pack使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类struct.Struct
的用法示例。
在下文中一共展示了Struct.pack方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: make_data
# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import pack [as 别名]
def make_data(self, data):
tabledict = self.table_by_name
coldict = self.col_by_uniname
# for tablename, rows in data.items():
# assert tablename in tabledict
# tabledict[tablename].set_rows(rows)
for table in self._tables:
tablename = table.name
table.set_rows(data[tablename])
package_header_struct = Struct(S_PACKAGE_HEADER_STRUCT)
table_header_struct = Struct(S_TABLE_HEADER_STRUCT)
col_header_struct = Struct(S_COL_HEADER_STRUCT)
table_header_list = []
col_header_list = []
col_data_list = []
for table in self._tables:
table_len = table.get_data()
table_header_list.append(table_header_struct.pack(table_len))
if table_len:
for col_uniname in table.col_uninames:
col = coldict[col_uniname]
store_type, compression_id, data = col.get_data()
col_size = pitched_len(len(data), ALIGN_BYTES)
col_header_list.append(col_header_struct.pack(store_type, compression_id))
col_data_list.append(data)
self.logger.info("%s, %s, %s, %s", col_uniname, store_type, compression_id, col_size)
package_header = package_header_struct.pack(0, 0)
table_header_struct = ''.join(table_header_list)
col_header_struct = ''.join(col_header_list)
return make_aligned_blocks(ALIGN_BYTES, package_header, table_header_struct, col_header_struct, *col_data_list)
示例2: array_packing
# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import pack [as 别名]
def array_packing(arrdef, *more_arrdef):
"""pack mulltiple arrays into same str
take care of alignments between arrays
"""
arrtype, arr = arrdef
mystruct = Struct(arrtype)
last_bytes = mystruct.size
cur_size = last_bytes * len(arr)
mybuffer = StringIO()
mybuffer.write(''.join(mystruct.pack(val) for val in arr))
for arrtype, arr in more_arrdef:
mystruct = Struct(arrtype)
cur_bytes = mystruct.size
if cur_bytes > last_bytes:
# align the string
fill_bytes = align2pitch(cur_size, cur_bytes)
mybuffer.write(ALIGN_CHAR * fill_bytes)
cur_bytes += fill_bytes
# write this arr
cur_size = last_bytes * len(arr)
mybuffer.write(''.join(mystruct.pack(val) for val in arr))
# leave notes
last_bytes = cur_bytes
rtn = mybuffer.getvalue()
mybuffer.close()
return rtn
示例3: _get_index_translation_table
# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import pack [as 别名]
def _get_index_translation_table(self):
"""Trying to validate/create the index table."""
start = time()
struct = Struct("I")
try:
with open(self.res("trans_table"), "r") as table:
table.seek(-4, os.SEEK_END)
position = table.tell()
self.task_size = position / 4
result = table.read(4)
result = struct.unpack(result)[0]
if result != 0:
print "index translation table was incomplete. regenerating!"
print "wasted %f seconds" % (time() - start)
start = time()
raise IOError
print "validated index file from hard drive"
except IOError:
count = 0
with open(self.res("trans_table"), "w") as table:
for num in fixed_bits(self.digits, self.bits_set):
table.write(struct.pack(num))
count += 1
# add a "finished" zero-fourbyte
table.write(struct.pack(0))
self.task_size = count
print "wrote index translation table to file"
print "took %f seconds for index translation table" % (time() - start)
示例4: inner_loop
# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import pack [as 别名]
def inner_loop(self):
if self.task_size == 0:
print "already calculated everything."
return
self.outfile = open(self.res("output"), "a")
outfile = self.outfile
neigh = self.neigh
stats_step = max(10, self.task_size / 2000)
packstruct = Struct("q")
cachesize = self.cachesize
cachecontents = len(self.cache)
print "writing out the size of the data dictionary every %d steps" % stats_step
print "goint to calculate %d numbers." % (self.task_size)
last_time = time()
iterator = self.number_iter
care_about_ordering = False
for index, number in iterator:
if self.cache[number] == 0:
representant, (path, rule_arr), everything = minimize_rule_number(neigh, number)
everything = everything.keys()
everything.remove(number)
try:
everything.remove(representant)
except ValueError:
pass
if len(everything) > 0:
lowest = everything[0] # try lowering the number of inserted high numbers
for num in everything:
if num > number and cachecontents < cachesize and (num < lowest or not care_about_ordering):
if self.cache[num] == 0:
self.cache[num] = representant
cachecontents += 1
lowest = num
if number == representant:
outfile.write(packstruct.pack(-len(everything)))
else:
outfile.write(packstruct.pack(representant))
else:
self.cachehits += 1
if cachecontents > self.max_cache_fill:
self.max_cache_fill = cachecontents
if cachecontents > 0.75 * cachesize:
care_about_ordering = True
cachecontents -= 1
val = self.cache[number]
del self.cache[number]
self.outfile.write(packstruct.pack(val))
if index % stats_step == 0:
endtime, last_time = time() - last_time, time()
self.timings.write("%f\n" % ((endtime * 1000) / stats_step))
self.items_done += 1
示例5: main
# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import pack [as 别名]
def main():
(archstr, inputfn, outputfn, vmaddr) = parse_options()
arch = Arch(archstr)
with open(inputfn, "rb") as fin, open(outputfn, "wb") as fout:
fin.seek(0, os.SEEK_END)
filesize = fin.tell()
fin.seek(0, os.SEEK_SET)
excess = 16 - (filesize & 16)
filesize += excess
endian = arch.endian
is64bit = arch.is64bit
# prepare mach_header(_64)
cputype = arch.cputype
cpusubtype = arch.cpusubtypePacked
if is64bit:
magic = 0xFEEDFACF
mach_header = Struct(endian + "7I4x")
else:
magic = 0xFEEDFACE
mach_header = Struct(endian + "7I")
# prepare segment_command(_64)
if is64bit:
segment_command = Struct(endian + "2I16s4Q4I")
cmd = LC_SEGMENT_64
else:
segment_command = Struct(endian + "2I16s8I")
cmd = LC_SEGMENT
cmdsize = segment_command.size
protlevel = 5
# prepare section(_64)
if is64bit:
section_stru = Struct(endian + "16s16s2Q7I4x")
else:
section_stru = Struct(endian + "16s16s9I")
cmdsize += section_stru.size
fileoff = cmdsize + mach_header.size
header_bytes = mach_header.pack(magic, cputype, cpusubtype, 1, 1, cmdsize, 1)
fout.write(header_bytes)
segment_bytes = segment_command.pack(cmd, cmdsize, "__TEXT", vmaddr, filesize, fileoff, filesize, 5, 5, 1, 0)
fout.write(segment_bytes)
section_bytes = section_stru.pack("__text", "__TEXT", vmaddr, filesize, fileoff, 4, 0, 0, 0x80000400, 0, 0)
fout.write(section_bytes)
copyfileobj(fin, fout)
fout.write(b"\0" * excess)
示例6: write
# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import pack [as 别名]
def write(filename, mesh):
ppack = Struct('fff') #float3
npack = ppack
ipack = Struct('H') #ushort
pbuffer = BytesIO()
nbuffer = BytesIO()
ibuffer = BytesIO()
reindex = {}
total = 0
vertices = mesh.vertices
for face in mesh.faces:
indices = face.vertices
if len(indices) == 3:
indices = [indices[0], indices[2], indices[1]]
if not face.use_smooth:
N = face.normal
for index in indices:
V = vertices[index].co
pbuffer.write( ppack.pack(V.x, V.y, V.z) )
nbuffer.write( npack.pack(N.x, N.y, N.z) )
ibuffer.write( ipack.pack(total) )
total += 1
else:
for index in indices:
if index not in reindex:
reindex[index] = total
total += 1
V = vertices[index].co
N = vertices[index].normal
pbuffer.write( ppack.pack(V.x, V.y, V.z) )
nbuffer.write( npack.pack(N.x, N.y, N.z) )
ibuffer.write( ipack.pack( reindex[index] ) )
else:
raise Exception("Untriangulated face.")
try:
os.mkdir(filename)
except OSError: pass # probably already exists
file = open(filename + '\\position', 'wb')
file.write( pbuffer.getvalue() )
file.close()
file = open(filename + '\\normal', 'wb')
file.write( nbuffer.getvalue() )
file.close()
file = open(filename + '\\index', 'wb')
file.write( ibuffer.getvalue() )
file.close()
示例7: write_op2
# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import pack [as 别名]
def write_op2(self, f, is_mag_phase=False):
#print('data_code =', self.data_code)
self._write_table_header(f)
if isinstance(self.nonlinear_factor, float):
op2_format = '%sif' % (7 * self.ntimes)
else:
op2_format = '2i6f' * self.ntimes
s = Struct(op2_format)
node = self.node_gridtype[:, 0]
gridtype = self.node_gridtype[:, 1]
format_table4_1 = Struct(b'9i')
format_table4_2 = Struct(b'3i')
# table 4 info
nnodes = self.data.shape[0]
nnodes_device = self.node_gridtype[:, 0] * 10 + self.device_code
#(2+6) => (node_id, gridtypei, t1i, t2i, t3i, r1i, r2i, r3i)
ntotal = self.ntimes * nnodes * (2 + 6)
table_num = 3
for itime in xrange(self.ntimes):
self._write_op2_header(f, table_num, itime)
# record 4
header = [4, 0, 4,
4, -table_num - 1, 4,
4, 4 * ntotal, 4]
f.write(format_table4_1.pack(*header))
t1 = self.data[itime, :, 0]
t2 = self.data[itime, :, 1]
t3 = self.data[itime, :, 2]
r1 = self.data[itime, :, 3]
r2 = self.data[itime, :, 4]
r3 = self.data[itime, :, 5]
i = 0
for node_id, gridtypei, t1i, t2i, t3i, r1i, r2i, r3i in izip(nnodes_device, gridtype, t1, t2, t3, r1, r2, r3):
vals = (node_id, gridtypei, t1i, t2i, t3i, r1i, r2i, r3i)
#grid = nodeID*10+device_code
f.write(s.pack(*vals))
table_num -= 2
header = [4, 4 * ntotal, 4]
f.write(format_table4_2.pack(*header))
示例8: write_binary_stl
# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import pack [as 别名]
def write_binary_stl(self, stl_filename):
"""Write an STL binary file."""
f = open(stl_filename, "wb")
if hasattr(self, 'header'):
self.header.ljust(80, '\0')
f.write(self.header)
else:
header = '%-80s' % stl_filename
f.write(pack('80s', header))
a = [0.,0.,0.]
b = [0.,0.,0.]
c = [0.,0.,0.]
nelements, three = self.elements.shape
f.write(pack('i', nelements))
elements = self.elements
p1 = self.nodes[elements[:, 0], :]
p2 = self.nodes[elements[:, 1], :]
p3 = self.nodes[elements[:, 2], :]
a = p2 - p1
b = p3 - p1
n = cross(a, b)
del a, b
#n /= norm(n, axis=1)
s = Struct('12fH')
for eid, element in enumerate(elements):
data = s.pack(n[eid, 0], n[eid, 1], n[eid, 2],
p1[eid, 0], p1[eid, 1], p1[eid, 2],
p2[eid, 0], p2[eid, 1], p2[eid, 2],
p3[eid, 0], p3[eid, 1], p3[eid, 2], 0)
f.write(data)
f.close()
示例9: write_records
# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import pack [as 别名]
def write_records(records, format, f):
"""
Write a sequence of iterables to a binary file
"""
record_struct = Struct(format)
for rec in records:
f.write(record_struct.pack(*rec))
示例10: parseLine
# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import pack [as 别名]
def parseLine( self, line ):
"Parse a gcode line."
binary16ByteRepository = self.binary16ByteRepository
splitLine = line.split()
if len( splitLine ) < 1:
return
firstWord = splitLine[ 0 ]
if len( firstWord ) < 1:
return
firstLetter = firstWord[ 0 ]
if firstLetter == '(':
return
feedRateInteger = getIntegerFromCharacterLengthLineOffset( 'F', 0.0, splitLine, binary16ByteRepository.feedRateStepLength.value )
iInteger = getIntegerFromCharacterLengthLineOffset( 'I', 0.0, splitLine, binary16ByteRepository.xStepLength.value )
jInteger = getIntegerFromCharacterLengthLineOffset( 'J', 0.0, splitLine, binary16ByteRepository.yStepLength.value )
xInteger = getIntegerFromCharacterLengthLineOffset( 'X', binary16ByteRepository.xOffset.value, splitLine, binary16ByteRepository.xStepLength.value )
yInteger = getIntegerFromCharacterLengthLineOffset( 'Y', binary16ByteRepository.yOffset.value, splitLine, binary16ByteRepository.yStepLength.value )
zInteger = getIntegerFromCharacterLengthLineOffset( 'Z', binary16ByteRepository.zOffset.value, splitLine, binary16ByteRepository.zStepLength.value )
sixteenByteStruct = Struct( 'cBhhhhhhBc' )
# print( 'xInteger' )
# print( xInteger )
flagInteger = getIntegerFlagFromCharacterSplitLine( 'X', splitLine )
flagInteger += 2 * getIntegerFlagFromCharacterSplitLine( 'Y', splitLine )
flagInteger += 4 * getIntegerFlagFromCharacterSplitLine( 'Z', splitLine )
flagInteger += 8 * getIntegerFlagFromCharacterSplitLine( 'I', splitLine )
flagInteger += 16 * getIntegerFlagFromCharacterSplitLine( 'J', splitLine )
flagInteger += 32 * getIntegerFlagFromCharacterSplitLine( 'F', splitLine )
packedString = sixteenByteStruct.pack( firstLetter, int( firstWord[ 1 : ] ), xInteger, yInteger, zInteger, iInteger, jInteger, feedRateInteger, flagInteger, '#' )
self.output.write( packedString )
示例11: putPacket
# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import pack [as 别名]
def putPacket(self, payload, flags=0):
if flags & 0b00000001:
payload = compress(payload)
# length calculations
blocklength = self.cipherscheme.block_size
payloadlength = len(payload)
paddinglength = 4 + blocklength - (10 + payloadlength) % blocklength
packetlength = 6 + payloadlength + paddinglength
# create packet
fields = (
packetlength,
paddinglength,
flags,
payload,
self.prng.read(paddinglength)
)
packetformat = Struct('!LBB%ds%ds' % (payloadlength, paddinglength))
encpacket = bytearray(self.encipher.encrypt(packetformat.pack(*fields)))
# update message authentication
self.ehmac.update(self.longformat.pack(self.enseqno))
self.ehmac.update(buffer(encpacket))
self.enseqno += 1
# append the most recent digest
encpacket.extend(self.ehmac.digest())
# put packet on the wire
packet = buffer(encpacket)
while packet:
packet = packet[self.sock.send(packet):]
示例12: write_records
# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import pack [as 别名]
def write_records(records, format, f):
'''
Zapis sekwencji krotek do pliku binarnego ze strukturami
'''
record_struct = Struct(format)
for r in records:
f.write(record_struct.pack(*r))
示例13: BinStruct
# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import pack [as 别名]
class BinStruct(object):
_format = '!c'
_type = None
_min = None
_max = None
def __init__(self):
self.struct = SStruct(self._format)
self._custom_size = None
@property
def size(self):
return self.struct.size
@property
def custom_size(self):
return self._custom_size
@custom_size.setter
def custom_size(self, value):
self._custom_size = value
def unpack(self, string):
return self.struct.unpack(string)
def pack(self, string):
return self.struct.pack(string)
示例14: write_binary_stl
# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import pack [as 别名]
def write_binary_stl(self, stl_filename):
"""Write an STL binary file."""
infile = open(stl_filename, "wb")
if hasattr(self, 'header'):
self.header.ljust(80, '\0')
infile.write(self.header)
else:
header = '%-80s' % stl_filename
infile.write(pack('80s', header))
#avector = [0., 0., 0.]
#bvector = [0., 0., 0.]
#cvector = [0., 0., 0.]
nelements = self.elements.shape[0]
infile.write(pack('i', nelements))
elements = self.elements
p1 = self.nodes[elements[:, 0], :]
p2 = self.nodes[elements[:, 1], :]
p3 = self.nodes[elements[:, 2], :]
avector = p2 - p1
bvector = p3 - p1
n = cross(avector, bvector)
del avector, bvector
#n /= norm(n, axis=1)
s = Struct('12fH')
for eid, element in enumerate(elements):
data = s.pack(n[eid, 0], n[eid, 1], n[eid, 2],
p1[eid, 0], p1[eid, 1], p1[eid, 2],
p2[eid, 0], p2[eid, 1], p2[eid, 2],
p3[eid, 0], p3[eid, 1], p3[eid, 2], 0)
infile.write(data)
infile.close()
示例15: ULInt24
# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import pack [as 别名]
class ULInt24(StaticField):
"""
A custom made construct for handling 3-byte types as used in ancient file formats.
A better implementation would be writing a more flexable version of FormatField,
rather then specifically implementing it for this case
"""
__slots__ = ["packer"]
def __init__(self, name):
self.packer = Packer("<BH")
StaticField.__init__(self, name, self.packer.size)
def __getstate__(self):
attrs = StaticField.__getstate__(self)
attrs["packer"] = attrs["packer"].format
return attrs
def __setstate__(self, attrs):
attrs["packer"] = Packer(attrs["packer"])
return StaticField.__setstate__(attrs)
def _parse(self, stream, context):
try:
vals = self.packer.unpack(_read_stream(stream, self.length))
return vals[0] + (vals[1] << 8)
except Exception:
ex = sys.exc_info()[1]
raise FieldError(ex)
def _build(self, obj, stream, context):
try:
vals = (obj%256, obj >> 8)
_write_stream(stream, self.length, self.packer.pack(vals))
except Exception:
ex = sys.exc_info()[1]
raise FieldError(ex)