【发布时间】:2019-02-24 20:49:13
【问题描述】:
我尝试在 python3 中设置一个 mqtt 客户端。这不是我第一次这样做,但是我遇到了一个相当奇怪的行为。 当尝试从回调函数之一(on_connect 或 on_message)调用包含错误的函数时,python 不会抛出异常(至少没有打印),它只是停在那里。我结合了一个简短的例子,它重现了这种行为。
有人有想法吗?
import paho.mqtt.client as mqtt
import re
import os.path
import json
from termcolor import colored
client = mqtt.Client()
def func():
test = 1 + "1"
print("Should never reach that")
def on_connect(client, userdata, flags, rc):
"""Establishes connection to broker
"""
print("Connected to broker with result code " + str(rc))
client.subscribe("test")
def on_message(client,userdata,msg):
print("Recieved message on " + msg.topic)
params = {}
if msg.topic == "test":
print("Invoke func")
func()
if __name__ == "__main__":
client.on_connect = on_connect
client.on_message = on_message
client.connect("localhost",1883,60)
client.loop_forever()
这是向主题“test”发送消息时的输出:
Connected to broker with result code 0
Recieved message on test
Invoke func
当从 main 调用 func() 时,我得到了正确的 TypeError 抛出。所以有些东西在 paho 中捕获了这个异常。我查看了一个较旧的项目(尽管是 python2)并尝试重新创建该行为。那里的异常被正确抛出。我错过了什么?
编辑 我可以通过将 func() 调用放在 try 块中来捕获异常。但是,它不会在未被捕获时停止程序的执行。我不明白为什么
【问题讨论】:
标签: python exception mqtt paho