Paho MQTT Python客户端:没有引发异常,只是停止 [英] Paho MQTT Python Client: No exceptions thrown, just stops
问题描述
我尝试在python3中设置一个mqtt客户端.这不是我第一次这样做,但是我遇到了一个很奇怪的行为. 尝试从其中一个回调函数(on_connect或on_message)调用包含错误的函数时,python不会引发异常(至少不打印异常),而只是在此停止.我把一个简短的例子绑在一起,重现了这种行为.
I try to setup a mqtt client in python3. This is not the first time im doing this, however i came across a rather odd behaviour. When trying to call a function, which contains a bug, from one of the callback functions (on_connect or on_message), python does not throw an exception (at least it is not printed), it just stops there. I tied together a short example, that reproduces that behaviour.
有人有主意吗?
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"发送消息时的输出:
This is the output when sending a message to the topic "test":
Connected to broker with result code 0
Recieved message on test
Invoke func
当从main调用func()时,我抛出了正确的TypeError.所以有些东西在paho中捕获了此异常.我看了一个较旧的项目(虽然是python2),并试图重新创建该行为.在那里正确地抛出了异常.我想念什么?
When calling func() from main, i get the correct TypeError thrown. So something catches this exception in paho. I had a look at an olderproject (python2 though) and tried to recreate the behaviour. There the exception gets thrown correctly. What do i miss?
编辑 我可以通过将func()调用放在try块中来捕获异常.但是,如果未被捕获,它不会停止程序的执行.我不明白为什么
EDIT I can catch the exception by putting the func() call in a try block. How ever, it does not stop the execution of the program when not catched. I dont get why
推荐答案
这是由于on_message
函数是由网络线程调用的事实,它将把该调用包装在try
块中,以阻止on_message
中的错误停止该线程.
This will be due to the fact that the on_message
function is called by the network thread and it will be wrapping that call in a try
block to stop errors in on_message
from stopping that thread.
如果您想出错以停止应用程序,则应在on_message
中使用您自己的try
块并采取适当的措施.
If you want to an error to stop the app then you should use your own try
block in on_message
and behave appropriately.
这篇关于Paho MQTT Python客户端:没有引发异常,只是停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!