paho mqtt:使用 python 3 编译时输出不正确

paho mqtt: Incorrect ouput, when compiling with python 3

我想建立一个 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 中,消息负载现在被认为是一个字节数组(实际上它应该一直被处理)

这可以通过以下方式转换为字符串:

def on_message(client, userdata, message):
    payload = message.payload.decode()
    print("Received message '" + payload + "' on topic '"
          + message.topic + "' with QoS " + str(message.qos))

    if payload == "Hello":
        print("Received message #1. Do something.")
        # do something

    if payload == "World":
        print("Received message #2. Do something else.")
        # do something