mqtt_20.py

#!/usr/bin/python3
# ===================================================================
# From: www.steves-internet-guide.com/into-mqtt-python-client/
# ===================================================================

import paho.mqtt.client as mqtt
import time

broker   = 'localhost'
instance = 'tom'
topic    = 'sensors/#' 

# -------------------------------------------------------------------
# ---- callback function
# ---- it prints the received messages
# -------------------------------------------------------------------

def on_message(client, userdata, message):
    print('---------------------------------------------------')
    print("message received   = ", str(message.payload.decode("utf-8")))
    print("message topic      = ", message.topic)
    print("message qos        = ", message.qos)
    print("message retain flag= " ,message.retain)
    print('---------------------------------------------------')

# -------------------------------------------------------------------
# ---- main
# -------------------------------------------------------------------

print(f'creating new client instance {instance}')
client = mqtt.Client("tom")

print('attach function to callback')
client.on_message=on_message

print(f'connecting to broker {broker}')
client.connect(broker)

print('start loop')
client.loop_start()

print(f'subscribing to topic {topic}')
client.subscribe(topic,qos=0)

time.sleep(4)

client.loop_stop()