struct unpack(类型错误:需要像对象这样的字节,而不是'str“),解压缩列表?

时间:2018-08-12 00:59:30

标签: python python-3.x struct python-2to3

尝试使用Python 2内置的脚本,现在在Python 3中使用它,而未在系统中添加版本2。对于脚本,我得到的唯一错误与这一行的struct.unpack有关。...

def go_parse(rec_list):
    size = (len(rec_list) - 4) / 4
    first_arg = "%sI" % size
    return struct.unpack(first_arg, (rec_list.rstrip ('\xff\xff\xff\xff')))

在此函数的第4行,出现错误:

TypeError: a bytes-like object is required, not 'str'

我阅读了有关此内容的其他几篇文章,并且需要将其显式标记为字节,但是在这种情况下,我似乎无法弄清楚在何处显式标记该字节。我在SO上找到的其他示例herehere并没有提供太多解释。 struct pages似乎没有涵盖2-3的错误可能性……仅 struct.unpack(fmt,buffer)具有fmt和buffer这两个参数。基于这些示例,我尝试使用b以及在参数.strip的元组和元组之前的bytes将其明确标识为字节,作为第二个arg。我尝试将其返回为bytearray,但这似乎会产生相同的错误。

作为替代方案,我可以将所需的字节数据获取到列表中,如下所示,这是将列表解包的一种方法,尝试b'i'只是将i视为字节。

list1 = [b'\x03\x00\x00\x00\xff\xff\xff\xff',
b'\x07\x00\x00\x00\x06\x00\x00\x00\xff\xff\xff\xff']

print(struct.unpack('<s', bytes(i)))

字节长短不一,但所有结尾均为\ xff \ xff \ xff \ xff。我正在查看的数据是文本,只是试图将其恢复为文本。

1 个答案:

答案 0 :(得分:0)

我回答了自己的问题,花了一些时间在文档上,有人指出了正确的方向。

我生成了需要返回到文本进行显示的二进制数据列表,我使用了标准库codecs。我所有的二进制数据都保存到名为bin_list的列表中。

import codecs

bin_list = [b'Some Binary data', b'some more binary data']

for i in bin_list:    # used the loop to print each to new line, nice and neat
    print (codecs.decode(i, "utf-8", "ignore"))   # or any other conversion avilable on codecs.