Search code examples
pythonmqtt

How to exit mqtt forever_loop?


I created a program to receive data, recently.

And I want to break the loop When I receive a specific data.

For example, if I receive "1" to another machine, then my system will regard it as an illegal number, then it will break the loop to stop receiving data.

Here is my code in the below, and you can also see client.loop_stop() in my code. But it not works.

I have also tried sys.exit() in my code.

Although it works in this case, it is not suitable to be utilized in other situation.

So I am wondering about how to break the loop of the client, I don't want to close the whole system by sys.exit().

import paho.mqtt.client as mqtt
# This is the Subscriber
a=""
def on_connect(client, userdata, flags, rc):
  print("Connected with result code "+str(rc))
  client.subscribe("hello")

def on_message(client, userdata, msg):
    info=msg.payload.decode()
    print info
    if str(info)=='1':
      print "OK"
      client.loop_stop()


client = mqtt.Client()
client.connect("myIp",1883,60)

client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()

Solution

  • In order to stop loop_forever, you must use client.disconnect, not loop_stop.