我知道之前已经问过这个问题,但是不能让它为我工作。 我想要做的是发送一个带有我的消息的前缀,如下所示:
msg = pickle.dumps(message)
prefix = b'{:0>5d}'.format(len(msg))
message = prefix + msg
这给了我
AttributeError: 'bytes' object has no attribute 'format'
我尝试使用%
进行格式化和编码,但没有一个能够正常工作。
答案 0 :(得分:4)
你不能format
一个bytes
literal。您也无法将bytes
个对象与str
个对象连接起来。相反,将整个内容整合为str
,然后使用正确的编码将其转换为bytes
。
msg = 'hi there'
prefix = '{:0>5d}'.format(len(msg)) # No b at the front--this is a str
str_message = prefix + msg # still a str
encoded_message = str_message.encode('utf-8') # or whatever encoding
print(encoded_message) # prints: b'00008hi there'
或者,如果你是一个单行的粉丝:
encoded_message = bytes('{:0>5d}{:1}'.format(len(msg), msg), 'utf-8')
根据您对@Jan-Philip's answer的评论,您需要指定您要转移的字节数?鉴于此,您需要首先对消息进行编码,以便正确确定发送消息时的字节数。 The len
function produces a proper byte-count when called on bytes
,所以这样的东西应该适用于任意文本:
msg = 'ü' # len(msg) is 1 character
encoded_msg = msg.encode('utf-8') # len(encoded_msg) is 2 bytes
encoded_prefix = '{:0>5d}'.format(len(encoded_msg)).encode('utf-8')
full_message = encoded_prefix + encoded_msg # both are bytes, so we can concat
print(full_message) # prints: b'00002\xc3\xbc'
答案 1 :(得分:1)
编辑:我想我误解了你的问题。你的问题是你无法将长度转换为字节对象,对吧?
好的,你通常会以这种方式使用struct
模块:
struct.pack("!i", len(bindata)) + bindata
这将(binary!)消息的长度写入四字节整数对象。 pack()
的返回值是此对象(类型为bytes
)。要在接收端对此进行解码,您需要将消息的前4个字节准确读入字节对象。我们称之为first_four_bytes
。使用struct.unpack
进行解码,在这种情况下使用相同的格式说明符(!i):
messagesize, = struct.unpack("!i", first_four_bytes)
然后您确切知道以下有多少字节属于该消息:messagesize
。准确读取那么多字节,然后解码消息。
旧答案:
在Python 3中,__add__
运算符返回我们想要的内容:
>>> a = b"\x61"
>>> b = b"\x62"
>>> a + b
b'ab'