[英]struct unpack (Type Error: a byte like object is required, not 'str"), Unpack a List?
Attempting to use script that was built in Python 2, and now use it in Python 3 without adding a version 2 onto system. 尝试使用Python 2内置的脚本,现在在Python 3中使用它,而未在系统中添加版本2。 For the script, the only error I get is related to a struct.unpack at this line....
对于脚本,我得到的唯一错误与这一行的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')))
at line 4 of this function, I get the error: 在此函数的第4行,我得到了错误:
TypeError: a bytes-like object is required, not 'str'
I read several other posts regarding this, and that it needs to be explicitly labeled as bytes, but I cant seem to figure out where to explicitly label that in this context. 我阅读了有关此内容的其他几篇文章,并且需要将其显式标记为字节,但是在这种情况下,我似乎无法弄清楚在何处显式标记该字节。 The other examples on SO i found here and here , did not provide much of an explanation to it.
我在这里和这里找到的关于SO的其他示例对此没有提供太多解释。 The struct pages don't seem to cover the error possibilities of 2-3...Only that struct.unpack(fmt, buffer) has the two arguments of fmt and buffer.
struct页面似乎并未涵盖2-3的错误可能性...仅struct.unpack(fmt,buffer)具有fmt和buffer这两个参数。 Based on those examples, i have tried identifying this as bytes explicitly as a second arg using
b
, as well as bytes
before the arguments and on the tuple for the .strip. 基于这些示例,我尝试使用
b
明确标识为第二个arg bytes
,以及.strip参数和元组之前的字节。 I attempted return this as a bytearray
, but that seemed to produce the same errors. 我试图将其作为
bytearray
返回,但这似乎会产生相同的错误。
As an alternative, I am able to get the byte data I wanted into a list as shown below, what would be a way to get the list into unpack, attempt b'i' just looks at i as bytes. 或者,我可以将所需的字节数据放入列表中,如下所示,这是将列表拆包的一种方法,尝试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)))
The bytes are of varying length, but all end in \\xff\\xff\\xff\\xff. 字节的长度各不相同,但全部以\\ xff \\ xff \\ xff \\ xff结尾。 The data I am looking at is text, just trying to bring it back to text.
我正在查看的数据是文本,只是试图将其恢复为文本。
I answered my own question spending some time in the Documentation, and someone pointing me in the right direction. 我花了一些时间在文档中回答了自己的问题,有人指出了正确的方向。
Generating a list of binary data that needed to be brought back to text for display, I used the codecs , a standard library. 生成需要返回到文本进行显示的二进制数据列表,我使用了编解码器 (标准库)。 All my binary data was saved into a list named bin_list.
我所有的二进制数据都保存到名为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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.