【问题标题】:paho mqtt: Incorrect ouput, when compiling with python 3paho mqtt:使用 python 3 编译时输出不正确
【发布时间】: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


【解决方案1】:

这是因为在 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

【讨论】:

  • 谢谢。这行得通。但是我觉得最奇怪的是,paho-mqtt 的文档中没有提到这一点。
  • 我还注意到,当我在print() 语句中丢失str(message.qos) 并且只写+ message.qos 这部分代码根本不会编译。好像被跳过了一样。为什么在这种情况下程序没有崩溃,而只是简单地忽略命令?
猜你喜欢
  • 1970-01-01
  • 2018-03-17
  • 2014-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-19
  • 2021-10-15
相关资源
最近更新 更多