mqtt 客户端 python_Paho MQTT 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.

Does someone has an idea?

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()

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

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?

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

解决方案

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.

If you want to an error to stop the app then you should use your own try block in on_message and behave appropriately.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值