Paho MQTT Python Client: No exceptions thrown, just stops

2024/10/14 11:19:40

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 mqttimport re
import os.pathimport json
from termcolor import coloredclient = 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_connectclient.on_message = on_messageclient.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

Answer

For anybody who comes across this and wonders why all exceptions inside of a mqtt callback are not thrown or at least not visible: In contrast to the python2 version of paho, the clients already catches ALL exceptions that occur when calling on of the user set callback functions. The output of this catch is then outputted to the on_log callback function. If this is not implemented by the user, there will be no visible output. So just add

def on_log(client, userdata, level, buff):print(buff)mqttc.on_log = on_log

to your code, to print out the exception.

https://en.xdnf.cn/q/69421.html

Related Q&A

SSH Key-Forwarding using python paramiko

We currently run a script on our desktop that uses paramiko to ssh to a remote linux host. Once we are on the remote linux host we execute another command to log into another remote machine. What we wa…

Is it possible to ignore Matplotlib first default color for plotting?

Matplotlib plots each column of my matrix a with 4 columns by blue, yellow, green, red.Then, I plot only the second, third, fourth columns from matrix a[:,1:4]. Is it possible to make Matplotlib ignore…

`sock.recv()` returns empty string when connection is dead on non-blocking socket

I have a non-blocking socket in Python called sock. According to my understanding the recv() method should raise an exception if the connection has been closed by the peer, but it returns an empty stri…

Iteration order with pandas groupby on a pre-sorted DataFrame

The SituationIm classifying the rows in a DataFrame using a certain classifier based on the values in a particular column. My goal is to append the results to one new column or another depending on cer…

How do I pass an exception between threads in python

I need to pass exceptions across a thread boundary.Im using python embedded in a non thread safe app which has one thread safe call, post_event(callable), which calls callable from its main thread.I am…

How to check if a docker instance is running?

I am using Python to start docker instances.How can I identify if they are running? I can pretty easily use docker ps from terminal like:docker ps | grep myimagenameand if this returns anything, the i…

Retrieving facets and point from VTK file in python

I have a vtk file containing a 3d model,I would like to extract the point coordinates and the facets.Here is a minimal working example:import vtk import numpy from vtk.util.numpy_support import vtk_to_…

Tensorflow: feed dict error: You must feed a value for placeholder tensor

I have one bug I cannot find out the reason. Here is the code:with tf.Graph().as_default():global_step = tf.Variable(0, trainable=False)images = tf.placeholder(tf.float32, shape = [FLAGS.batch_size,33,…

Pass many pieces of data from Python to C program

I have a Python script and a C program and I need to pass large quantities of data from Python script that call many times the C program. Right now I let the user choose between passing them with an AS…

Parse JavaScript to instrument code

I need to split a JavaScript file into single instructions. For examplea = 2; foo() function bar() {b = 5;print("spam"); }has to be separated into three instructions. (assignment, function ca…