【发布时间】:2018-11-10 15:43:28
【问题描述】:
我想建立一个 mqtt 连接。我想用 Python3 来做。
这是客户端代码的一部分:
def on_message(client, userdata, message):
print("Received message '" + str(message.payload) + "' on topic '"
+ message.topic + "' with QoS " + str(message.qos))
if message.payload == "Hello":
print("Received message #1. Do something.")
# do something
if message.payload == "World":
print("Received message #2. Do something else.")
# do something
我基本上是在给定主题下向该客户端发布消息“World”和“Hello”,但根据我使用的 python 版本,我收到不同的结果。
这是我用python2编译时的输出:(这是我想要的输出)
pi@raspberrypi:~/Desktop $ python Client.py Connection returned result: 0 Received message 'Hello' on topic 'Wulff/test' with QoS 0 Received message #1. Do something. Received message 'World' on topic 'Wulff/topic' with QoS 0 Received message #2. Do something else.
这是我用 python3 编译时的输出:
pi@raspberrypi:~/Desktop $ python3 Client.py Connection returned result: 0 Received message 'b'Hello'' on topic 'Wulff/test' with QoS 0 Received message 'b'World'' on topic 'Wulff/topic' with QoS 0 Received message 'b'Hello'' on topic 'Wulff/test' with QoS 0 Received message 'b'World'' on topic 'Wulff/topic' with QoS 0`
我不明白为什么程序无法识别此处的消息负载。
使用不同版本的python运行程序需要注意什么?我已经在 Python2 和 Python3 上安装了必要的模块。
【问题讨论】:
-
在 Python 3 中,您必须解码有效载荷:
message.payload.decode()。如果您使用的不是默认编码 (UTF-8),则必须将其作为参数提供给decode()。
标签: python-3.x python-2.7 mqtt paho