The best freely available python library is the Paho Python client.
It can be installed using:
pip install paho-mqtt
Simple example code could then look like (using the current Paho v2 callback API):
import paho.mqtt.client as mqtt
# Define event callbacks
def on_connect(client, userdata, flags, reason_code, properties):
if reason_code == 0:
print("Connected successfully.")
else:
print("Connection failed: "+str(reason_code))
def on_publish(client, userdata, mid, reason_code, properties):
print("Message "+str(mid)+" published.")
def on_subscribe(client, userdata, mid, reason_code_list, properties):
print("Subscribe with mid "+str(mid)+" received.")
def on_message(client, userdata, msg):
print("Message received on topic "+msg.topic+" with QoS "+str(msg.qos)+" and payload "+str(msg.payload))
mqttclient = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
# Assign event callbacks
mqttclient.on_connect = on_connect
mqttclient.on_publish = on_publish
mqttclient.on_subscribe = on_subscribe
mqttclient.on_message = on_message
# Connect
mqttclient.username_pw_set(yourUserName, yourPassword)
mqttclient.connect(hostname, port)
# Start subscription
mqttclient.subscribe(yourRootTopic)
# Publish a message
mqttclient.publish(yourRootTopic, "Hello World Message!")
# Block forever, dispatching callbacks as messages arrive
mqttclient.loop_forever()