如何为MQTT Python客户端全局使用msg.payload?

时间:2016-05-14 09:41:31

标签: python mqtt

我想询问是否有一种方法可以全局使用msg.payload而不是仅仅在回调函数中使用# The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) # I usually then specify my steps here, but how can I use the variable outside? client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message

Bellow是基本的回调函数:

def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))
    return msg.payload

global_data= on_message
# do whatever I want with the data. I already tried to do this but it didn't work because 
# the client loops forever using client.loop_forever()

例如,我想做这样的事情:

"?foo=bar&nonfoo=bar&foo=bar"

1 个答案:

答案 0 :(得分:1)

使用client.start_loop功能代替client.loop功能。这将在一个单独的线程上启动网络循环,允许您在主线程上执行自己的操作。

然后,您可以在回调中将全局变量的值设置或更改为msg.payload的内容。

E.g。

global_var

def on_message(client, userdata, msg): 
  global global_var
  print(msg.topic+" "+str(msg.payload))
  global_var = msg.payload