在 python 中使用 paho mqtt 处理收到的消息

Processing a received message using paho mqtt in python

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("/leds/pi")

def on_message(client, userdata, msg):
    if msg.topic == '/leds/pi':
        print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("localhost", 1883, 60)
client.loop_start()

我使用这个基本代码来订阅主题和接收消息。每当收到消息时,都会调用 on_message 函数。我需要能够在函数外部访问 msg.payload 并将其存储到变量中。只要收到消息,变量中的值就应该更新。我试图将 msg.payload 存储到函数内的全局变量并访问它,但是,这给出了一个错误,指出该变量未定义。请帮忙

I need to be able to access the msg.payload outside the function and store it to a variable.

您需要一个全局变量,例如:

myGlobalMessagePayload = ''   #HERE!

def on_message(client, userdata, msg):
    global myGlobalMessagePayload
    if msg.topic == '/leds/pi':
        myGlobalMessagePayload  = msg.payload   #HERE!
        print(msg.topic+" "+str(msg.payload))