我想询问是否有一种方法可以全局使用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"
答案 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