How do I pass an exception between threads in python

2024/10/14 11:16:36

I need to pass exceptions across a thread boundary.

I'm 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 running a pygtk gui in a seperate thread, so when a button is clicked I post an event with post_event, and wait for it to finish before continuing. But I need the caller to know if the callee threw an exception, and raise it if so. I'm not too worried about the traceback, just the exception itself.

My code is roughly:

class Callback():def __init__(self,func,*args):self.func=funcself.args=argsself.event=threading.Event()self.result=Noneself.exception=Nonedef __call__(self):gtk.gdk.threads_enter()try:self.result=self.func(*self.args)except:#what do I do here? How do I store the exception?passfinally:gtk.gdk.threads_leave()self.event.set()def post(self):post_event(self)gtk.gdk.threads_leave()self.event.wait()gtk.gdk.threads_enter()if self.exception:raise self.exceptionreturn self.result

Any help appreciated, thanks.

Answer

#what do I do here? How do I store the exception?

Use sys.exc_info()[:2], see this wiki

Best way to communicate among threads is Queue. Have the main thread instantiate a Queue.Queue instance and pass it to subthreads; when a subthread has something to communicate back to the master it uses .put on that queue (e.g. a tuple with thread id, exception type, exception value -- or, other useful info, not necessarily exception-related, just make sure the first item of a tuple identifies the kind of info;-). The master can .get those info-units back when it wants, with various choices for synchronization and so on.

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

Related Q&A

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…

Converting all files (.jpg to .png) from a directory in Python

Im trying to convert all files from a directory from .jpg to .png. The name should remain the same, just the format would change.Ive been doing some researches and came to this:from PIL import Image im…

AssertionError: Gaps in blk ref_locs when unstack() dataframe

I am trying to unstack() data in a Pandas dataframe, but I keep getting this error, and Im not sure why. Here is my code so far with a sample of my data. My attempt to fix it was to remove all rows whe…

Python does not consider distutils.cfg

I have tried everything given and the tutorials all point in the same direction about using mingw as a compiler in python instead of visual c++.I do have visual c++ and mingw both. Problem started comi…

Is it possible to dynamically generate commands in Python Click

Im trying to generate click commands from a configuration file. Essentially, this pattern:import click@click.group() def main():passcommands = [foo, bar, baz] for c in commands:def _f():print("I a…

Different accuracy between python keras and keras in R

I build a image classification model in R by keras for R.Got about 98% accuracy, while got terrible accuracy in python.Keras version for R is 2.1.3, and 2.1.5 in pythonfollowing is the R model code:mod…