MQTT Python Client Library
Eclipse Paho Python 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 messages.
Install using the PyPi package management tool:
bash
pip install paho-mqtt
TIP
Currently, Paho Python has fully supported MQTT 5.0.
Quick Start Tutorial
This example contains the complete code of Paho Python in Python connecting to EMQX Broker, sending and receiving messages:
python
import paho.mqtt.client as mqtt
#Connection success callback
def on_connect(client, userdata, flags, rc):
print('Connected with result code '+str(rc))
client.subscribe('testtopic/#')
# Message receiving callback
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client()
# Specify callback function
client.on_connect = on_connect
client.on_message = on_message
# Establish a connection
client.connect('broker.emqx.io', 1883, 60)
# Publish a message
client.publish('emqtt',payload='Hello World',qos=0)
client.loop_forever()