How to capture trace in gevent

I spawned Greenlet and associated it with the callee. After some time, Greenlett fails with the Exception. The linked caller is called. This is all great!

Here's the problem:

Tracking for Exception appears on my console, as you would expect. But I want to do something with this trace inside the associated caller. How to access this trace inside a linked caller?

(My first instinct was to use traceback.extract_stack() , but it turned out that it provides tracing for the associated caller, not an exception.)

+6
source share
4 answers

Tracking is intentionally not saved when Greenlet dies. If it was saved, it will save many live objects, which are expected to be deleted, which is especially important if the object manages some resource (open file or socket).

If you want to keep the trace, you must do it yourself.

+15
source

The Greenlet object should have an exception property, which you can see:

http://www.gevent.org/gevent.html#gevent.Greenlet.exception

+1
source

Just make sure you grab the exception value for Greenlet and throw it outside of Greenlet, for example get returns either the return value or increases the internal exception.

 import traceback import gevent def fail(): return 0/0 gl = gevent.spawn(fail) try: gl.get() except Exception as e: stack_trace = traceback.format_exc() # here your stacktrace 

Gotta give you what you need.

+1
source

As an alternative to Steven Greenlet.link_exception using Greenlet.link_exception .

 import traceback import gevent def job(): raise Exception('ooops') def on_exception(greenlet): try: greenlet.get() except Exception: err = traceback.format_exc() # Do something with `err` g = gevent.spawn(job) g.link_exception(on_exception) 
0
source

Source: https://habr.com/ru/post/908382/


All Articles