python - 不能在 MQTT 客户端中调用 message.topic?
问题描述
我有这个问题,on_message
当我调用msg.topic
. 我没有收到错误,但打印语句不再执行,尽管正在发送新消息。
问题是什么?
import paho.mqtt.client as client
hostname = 'iot.eclipse.org'
topic = 'Mein/Topic'
def on_message(client, userdata, msg):
msg = msg.payload.decode()
print("topic:", msg.topic)
print("Received Message: {}".format(msg))
def on_connect(client, userdata, flags, rc):
print("Connection returned result: " + str(rc) +
"\n")
if rc == 0:
print("Listening now.\n")
client.subscribe(topic)
client = client.Client()
client.on_message = on_message
client.on_connect = on_connect
client.connect(hostname)
client.loop_forever()
解决方案
paho 客户端有一个内置的 try/expect 块,用于包装调用on_message
以防止行为不良的回调使网络线程崩溃。
如果你想知道你的代码在哪里失败,你可以在on_message
函数内部添加你自己的 try/expect 来显示问题。就像是:
def on_message(client, userdata, msg):
try:
msg = msg.payload.decode()
print("topic:", msg.topic)
print("Received Message: {}".format(msg))
expect Exception, e:
print(e)
推荐阅读
- python - 执行 groupby 时出错,然后使用 sum() 函数
- c++ - 如何切换真假?
- javascript - 在 ReactJS 组件中将图像转换为灰度或透明
- pdf - 覆盖 PDF 中的 ToUnicode Map 流
- mediawiki - MediaWiki:如何解析通过 API 检索到的“descriptionmsg”值?
- mysql - 在 Node.js 中使用日期过滤器查询失败
- r - 在R中两个栅格之间的散点图中绘制回归线和r2?
- ruby - 如何修复此错误:意外的 tSYMBEG,期待 do 或 '{' 或 '('
- java - java.io.NotSerializableException: android.app.PendingIntent
- python - 如何将方法行减少为循环?