我目前的任务是剖析包含P2P消息的tcpdump数据,并且我在获取并写入x86机器上的文件时遇到了问题。我的怀疑是,我有一个简单的终端问题,与我写到文件的字节。
我有一个字节列表,其中包含一段P2P视频,使用读取和处理。
bytes = [14, 254, 23, 35, 34, 67, etc... ]
我正在寻找一种方法来存储这些字节,目前保存在我的Python应用程序中的一个列表中的一个文件。
目前,我写的文章如下:
def writePiece(self, filename, pieceindex, bytes, ipsrc, ipdst, ts):
file = open(filename,"ab")
# Iterate through bytes writing them to a file if don't have piece already
if not self.piecemap[ipdst].has_key(pieceindex):
for byte in bytes:
file.write('%c' % byte)
file.flush()
self.procLog.info("Wrote (%d) bytes of piece (%d) to %s" % (len(bytes), pieceindex, filename))
# Remember we have this piece now in case duplicates arrive
self.piecemap[ipdst][pieceindex] = True
# TODO: Collect stats
file.close()正如您从for循环中看到的那样,我将字节以与从连线(即网络或大端顺序)处理它们的顺序相同的顺序写入文件。
可以说,作为片段的有效负载的视频在VLC :-D中不能很好地播放。
我认为我需要将它们转换为小字节顺序,但不确定用Python处理这个问题的最佳方法。
更新
为我找到的解决方案(编写适当处理endian问题的P2P片段)是:
def writePiece(self, filename, pieceindex, bytes, ipsrc, ipdst, ts):
file = open(filename,"r+b")
if not self.piecemap[ipdst].has_key(pieceindex):
little = struct.pack('<'+'B'*len(bytes), *bytes)
# Seek to offset based on piece index
file.seek(pieceindex * self.piecesize)
file.write(little)
file.flush()
self.procLog.info("Wrote (%d) bytes of piece (%d) to %s" % (len(bytes), pieceindex, filename))
# Remember we have this piece now in case duplicates arrive
self.piecemap[ipdst][pieceindex] = True
file.close()解决方案的关键是怀疑使用Python模块,特别是:
little = struct.pack('<'+'B'*len(bytes), *bytes) 感谢那些给出有帮助的建议的人。
发布于 2010-08-22 12:56:02
您还可以使用array.array
from array import array
f.write(array('B', bytes))而不是
f.write(struct.pack('<'+'B'*len(bytes), *bytes))一点收拾的时候
f.write(struct.pack('B' * len(bytes), *bytes))
# the < is redundant; there is NO ENDIANNESS ISSUE如果len(字节)是“大的”,它可能会更好
f.write(struct.pack('%dB' % len(bytes), *bytes)) 发布于 2010-08-04 14:35:12
为了节省一些工作,您可能希望使用bytearray (Python2.6及更高版本):
b = [14, 254, 23, 35]
f = open("file", 'ab')
f.write(bytearray(b))这将完成所有将0-255值转换为字节的工作,而不需要进行所有循环。
如果没有更多的信息,我就看不出你的问题是什么。如果数据确实是字节级的,那么endianness并不是一个问题,就像其他人所说的那样。
(顺便说一下,使用bytes和file作为变量名并不好,因为它隐藏了同名的内置程序)。
发布于 2010-08-04 13:54:27
这可能已经在Python文件Slurp w/ endian转换中得到了先前的回答。
https://stackoverflow.com/questions/3405972
复制相似问题