MQTT Python client library

Eclipse Paho PythonMQTT Python Client Library - 图1 (opens new window) is a Python language client library under the Eclipse Paho project, which can connect to MQTT Broker to publish messages, subscribe to topics and receive Published message.

Install using the PyPi package management tool:

  1. pip install paho-mqtt

Paho Python usage example

This example contains the complete code of Paho Python in Python connecting to EMQ X Broker, sending and receiving messages:

  1. import paho.mqtt.client as mqtt
  2. #Connection success callback
  3. def on_connect(client, userdata, flags, rc):
  4. print('Connected with result code '+str(rc))
  5. client.subscribe('testtopic/#')
  6. # Message receiving callback
  7. def on_message(client, userdata, msg):
  8. print(msg.topic+" "+str(msg.payload))
  9. client = mqtt.Client()
  10. # Specify callback function
  11. client.on_connect = on_connect
  12. client.on_message = on_message
  13. # Establish a connection
  14. client.connect('broker.emqx.io', 1883, 60)
  15. # Publish a message
  16. client.publish('emqtt',payload='Hello World',qos=0)
  17. client.loop_forever()

Paho Python MQTT 5.0 support

Currently, Paho Python is still adapting to MQTT 5.0 and has not yet been fully supported it.