こちらを参考にしました。
paho-mqtt 2.1.0
必要なライブラリーのインストール
sudo apt install python3-paho-mqtt
Publish
publish.py
#! /usr/bin/python
#
# publish.py
#
# Mar/31/2025
#
# ------------------------------------------------------------------
import paho.mqtt.publish as publish
import sys
sys.stderr.write("*** 開始 ***\n")
message = "Good Afternoon"
topic = "/paho/test/topic"
publish.single(topic, message, hostname="localhost")
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------
Subscribe
subscribe_callback.py
#! /usr/bin/python
#
# subscribe_callback.py
#
# Mar/31/2025
#
# ------------------------------------------------------------------
import paho.mqtt.subscribe as subscribe
import sys
# ------------------------------------------------------------------
def on_message_print(client, userdata, message):
print("%s %s" % (message.topic, message.payload))
userdata["message_count"] += 1
if userdata["message_count"] >= 5:
# it's possible to stop the program by disconnecting
client.disconnect()
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
topic = "/paho/test/topic"
subscribe.callback(on_message_print, topic, hostname="localhost", userdata={"message_count": 0})
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------
確認したバージョン
$ python --version
Python 3.12.7
テストに使ったスクリプト
go_pub.sh
BROKER="localhost"
TOPIC="/paho/test/topic"
#
echo $BROKER
message="{\"key\": \"A1B2C3D4\",\"version\": \"2025-3-31 AM 11:09\"}"
mosquitto_pub -d -t orz -m "${message}" \
-h $BROKER \
--topic $TOPIC
go_sub.sh
BROKER="localhost"
TOPIC="/paho/test/topic"
#
mosquitto_sub -d -h $BROKER --topic $TOPIC