Registry / http-networking / paho-mqtt

paho-mqtt

JSON →
library2.1.0pypypi✓ verified 23d ago

The Eclipse Paho MQTT Python Client library provides classes for applications to connect to an MQTT broker, publish messages, and subscribe to topics to receive messages. It supports MQTT versions 5.0, 3.1.1, and 3.1, and is designed for lightweight publish/subscribe messaging, suitable for IoT and M2M communication where bandwidth or code footprint is a concern. The current stable version is 2.1.0, with regular updates and an active development cadence as part of the Eclipse Foundation projects.

pip install paho-mqtt
INSTALL
IMPORT
SIG · PAHO-MQTT
P
paho-mqtt
http-networkingpythonv2.1.0
Install
1.6s avg
Import
124ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.1.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.128s · 18.3MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.6s · import 0.120s · 19MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Client
from paho.mqtt import client as mqtt_client
import paho.mqtt.client
Aliasing `paho.mqtt.client` to `mqtt_client` is a common convention for brevity and clarity.
CallbackAPIVersion
from paho.mqtt import client as mqtt_client
publish.single
from paho.mqtt import publish
subscribe.simple
from paho.mqtt import subscribe

This quickstart demonstrates how to connect to an MQTT broker, subscribe to a topic, and publish messages using the `paho-mqtt` client. It configures `on_connect` and `on_message` callbacks and uses `loop_start()` to handle network traffic in a background thread. It explicitly uses `CallbackAPIVersion.VERSION2` for modern MQTTv5 features and future compatibility. Environment variables are used for broker host/port for easy configuration.

import os import time from paho.mqtt import client as mqtt_client broker = os.environ.get('MQTT_BROKER_HOST', 'broker.hivemq.com') port = int(os.environ.get('MQTT_BROKER_PORT', 1883)) topic = os.environ.get('MQTT_TOPIC', "python/mqtt/test") client_id = f'python-mqtt-subscriber-{time.time()}' def on_connect(client, userdata, flags, rc, properties=None): if rc == 0: print("Connected to MQTT Broker!") client.subscribe(topic) else: print(f"Failed to connect, return code {rc}\n") def on_message(client, userdata, msg): print(f"Received `{msg.payload.decode()}` from `{msg.topic}`") def run(): # Use CallbackAPIVersion.VERSION2 for MQTTv5 compatibility and future-proofing client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2, client_id) # Optional: Set username/password if your broker requires it # client.username_pw_set(os.environ.get('MQTT_USERNAME', ''), os.environ.get('MQTT_PASSWORD', '')) client.on_connect = on_connect client.on_message = on_message client.connect(broker, port) client.loop_start() # Start background thread for network traffic # Publish a message after connection is established msg_count = 0 while True: time.sleep(1) msg = f"messages: {msg_count}" result = client.publish(topic, msg) status = result[0] if status == 0: print(f"Sent `{msg}` to topic `{topic}`") else: print(f"Failed to send message to topic {topic}") msg_count += 1 if msg_count >= 5: # Stop after 5 messages for quickstart example break client.loop_stop() # Stop the background thread client.disconnect() print("Disconnected from MQTT Broker.") if __name__ == '__main__': run()
Debug
Known issues
breakingVersion 2.0.0 introduced versioned user callbacks. If you omit the `callback_api_version` argument when creating `mqtt_client.Client`, it might default to `VERSION1` for positional arguments, leading to `Unsupported callback API version` errors, especially when migrating. In v2.1.0, it defaults to `VERSION1` if positional arguments are used, but `VERSION2` is recommended.
fix
Initialize the client with `mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2, client_id)`. If you need to retain older callback signatures, explicitly use `mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION1, client_id)` but plan for migration to `VERSION2` as `VERSION1` is deprecated and will be removed in v3.0.
affects: >=2.0.0
breakingVersion 2.0.0 dropped official support for Python 2.7, 3.5, and 3.6. The minimum supported Python version is now 3.7.
fix
Upgrade your Python environment to version 3.7 or newer.
affects: >=2.0.0
breakingThe `connect_srv()` method signature changed in version 2.0.0 to include an additional `bind_port` parameter.
fix
Update calls to `connect_srv()` to include the `bind_port` argument.
affects: >=2.0.0
gotchaWhen checking return codes (e.g., from `on_connect` or `publish`), version 2.0.0 introduced `IntEnum` objects (like `ReasonCode` and `MQTT_ERR_SUCCESS`) instead of raw integers. Direct comparison using `is` (e.g., `rc is 0`) will likely fail, while `==` (e.g., `rc == 0`) will work correctly.
fix
Always use `==` for comparison with return codes (e.g., `if rc == 0:`).
affects: >=2.0.0
gotchaFor non-durable MQTT clients, subscriptions are lost if the connection to the broker drops and is re-established. Placing subscription logic outside the `on_connect` callback can lead to missed messages after a reconnection.
fix
Always include `client.subscribe()` calls within your `on_connect` callback function. This ensures that subscriptions are automatically renewed upon successful reconnection to the broker.
affects: All versions
deprecatedThe `CallbackAPIVersion.VERSION1` (the historical API used before v2.0.0) is deprecated and is scheduled for removal in `paho-mqtt` version 3.0.
fix
Migrate your callback functions to use the `CallbackAPIVersion.VERSION2` signature and explicitly pass `mqtt_client.CallbackAPIVersion.VERSION2` to the `Client` constructor to prepare for future library updates.
affects: >=2.0.0
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'paho'
The `paho-mqtt` library is either not installed, or installed in a different Python environment than the one being used, or a local file named `paho.py` shadows the actual library module.
fix
Ensure `paho-mqtt` is installed in the correct environment by running `pip install paho-mqtt` (or `pip3 install paho-mqtt` for Python 3). Also, check that no script in the current directory or Python path is named `paho.py` or `paho/mqtt.py` that could cause a naming conflict.
ConnectionRefusedError: [Errno 111] Connection refused
This error indicates that the client attempted to connect to an MQTT broker, but the connection was actively refused by the target machine. This typically happens if no MQTT broker is running at the specified host and port, or a firewall is blocking the connection.
fix
Verify that an MQTT broker (e.g., Mosquitto) is running on the specified host and port, and that network connectivity and firewall rules allow the connection. Also, ensure the correct host and port are being used in the client's `connect()` method.
AttributeError: 'module' object has no attribute 'Client'
This error commonly occurs when trying to instantiate the MQTT client using `mqtt.client()` instead of `mqtt.Client()`, due to incorrect capitalization of the `Client` class, or if a user's file is named `paho.py` or `client.py`, causing a module name collision.
fix
Correct the instantiation to `client = mqtt.Client()` with a capital 'C'. Also, check that your Python script filename is not `paho.py`, `client.py`, or any other name that conflicts with the library's module structure.
BrokenPipeError: [Errno 32] Broken pipe
This error occurs when the client tries to write data (e.g., publish a message) to a socket that has been unexpectedly closed by the peer (the MQTT broker), often due to a network disconnection or the broker going offline.
fix
Ensure the client's network loop (e.g., `client.loop_start()` or `client.loop_forever()`) is running to handle reconnections automatically. Implement robust error handling around publish calls and potentially use `on_disconnect` callbacks to detect disconnections and manage reconnection logic.
MQTT_ERR_NO_CONN
This is a `paho-mqtt` internal error code (return code 4) indicating that a publish or subscribe operation was attempted when the client was not connected to the MQTT broker.
fix
Ensure the client has successfully connected to the broker before attempting to publish or subscribe. Use `client.loop_start()` or `client.loop_forever()` to manage the network connection in a background thread, which also handles automatic reconnections. Check the return code of `client.connect()` and handle connection failures in the `on_connect` callback.
Upgrade
Version history
2.1.0latest on PyPI · released Apr 29, 2024
Audit
Dependencies
pythonrequiredRequires Python 3.7 or newer. Support for Python 2.7, 3.5, and 3.6 was dropped in version 2.0.0.
Agent activity
19 hits · last 30 days
node
14
OpenAI (training)
1
Resources
paho-mqtt — pip install paho-mqtt · libregistry