@for ever 2012-06-25
在python32版本下面,下面的代码:
[python] view plaincopy
msg = pack(">H%ds" % len(reason), code, reason)
执行后出现如下的错误:
[plain] view plaincopy
struct.error: argument for 's' must be a bytes object
做如下修改,错误解决:
[python] view plaincopy
msg = pack(">H%ds" % len(reason), code, reason.encode('utf-8'))
[python] view plaincopy
关于struct.pack函数,参数个数是无限的。第一个参数定义打包格式,
剩余的所有参数都是要打包的内容。
第一个格式参数具体写法如下:
Format c Type
Python Note
x pad byte no value
c char string of length 1
b signedchar integer
B unsignedchar
integer
? _Bool bool (1)
h short integer
H unsignedshort
integer
i int integer
I unsignedint
integer or long
l long integer
L unsignedlong
long
q longlong long (2)
Q unsignedlonglong
long (2)
f float float
d double float
s char[] string
p char[] string
P void* long
此外,还包含相应的大/小端设置(如果忽略该设置,默认
@ native native
= native standard
< little-endian
standard
> big-endian standard
! network (= big-endian)
standard
@forandever 2012-6-25
3
down vote
favorite
I am attempting to execute the code:
values = (1, 'ab', 2.7)
s.struct.Struct('I 2s f')
packed = s.pack(*values)
But I keep getting the error:
Traceback (most recent call last):
File "", line 1, in
struct.error: argument for 's' must be a bytes object
Why? How do I fix this?
With Python 3, 'ab' isn't a bytes object, what was called a str on Python 2, it's unicode. You need to use:
values = (1, b'ab', 2.7)
which tells Python that 'ab' is a byte literal. See PEP 3112 for more info.
shareimprove this answer
answered Apr 10 '12 at 3:09
agf
55.1k11123145
2
This answer should be marked as THE answer to the question. – rbaleksandar Sep 29 '13 at 11:33