今天看到的struct 照书上的操作
>>> data = struct.pack('>i4sh', 7, 'spam', 8) # Make packed binary data
就提示如下的出错信息
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
data = struct.pack('>i4sh', 7, 'spam', 8) # Make packed binary data
struct.error: argument for 's' must be a bytes object
参数 's' 必须是一个字节型对象 所以如下修改即可
>>> data = struct.pack('>i4sh', 7, 'spam'.encode('utf-8'), 8) # Make packed binary data
pack的函数原型:
struct.pack(fmt, v1, v2, ...)
Return a bytes object containing the values v1, v2, ... packed according to the format string fmt. The arguments must match the values required by the format exactly.
即第一项表示的是格式 如上 '>i4sh' 表示的是大端法(>), int(i), 4s(4个字符的字符串), h(short)
格式的话可以在Python的帮助手册中查看(建议) 也可以 help(struct) 来查看
浙公网安备 33010602011771号