pythongeventspawngreenlets

Remove stacktrace from python gevent output


I'm new to python and trying to remove/trim gevent stacktrace output when an exception is raised. I read somewhere that I can make it happen by using AsyncResult, however it seems like I can't figure out how to use this.

Here is an example I started with and iterated over to make it similar to the real code I'm troubleshooting, but I got stuck in the last phase when I tried to add my_decor to work(). Any help fixing this is much appreciated.

from gevent.event import AsyncResult
import gevent
from functools import wraps


def my_decor(k, *args, **kwargs):
    @wraps(k)
    def wrapper(*args, **kwargs):
        r = AsyncResult()
        try:
            value = k()
        except Exception as e:
            r.set_exception(e)
        else:
            r.set(value)
        return r.exception or r.value
    result = gevent.spawn(wrapper, k)
    return result


def f():
    def foo():
        if True:
                raise Exception('tttttttt')
    return foo


def p():
    def bar():
        if True:
                raise Exception('ppppppppppppp')
    return bar


@my_decor
def work():
    foo1 = gevent.spawn(f())
    bar1 = gevent.spawn(p())
    gevent.joinall([foo1, bar1])
    return foo1.get() or bar1.get()

Solution

  • Found the answer, figured it might be a help to those with the same problem.

    from gevent.event import AsyncResult
    import gevent
    from functools import wraps
    
    
    def my_decor(k):
        @wraps(k)
        def wrapper(*args, **kwargs):
            r = AsyncResult()
            try:
                value = k(*args, **kwargs)
            except Exception as e:
                r.set_exception(e)
            else:
                r.set(value)
            return r.exception or r.value
        return wrapper
    
    
    def f(msg):
        @my_decor
        def foo():
            if True:
                raise Exception('tttttttt %s' % msg)
    #           print('test')
        return foo
    
    
    def p(msg):
        @my_decor
        def bar():
            if True:
                raise Exception('ppppppppppppp %s', msg)
        return bar
    
    
    def work():
        test = "test"
        seti = "set"
        foo1 = gevent.spawn(f(test))  # returns a function that coroutine uses
        bar1 = gevent.spawn(p(seti))
        gevent.joinall([foo1, bar1])
        return foo1.get() or bar1.get()
    
    
    res = work()
    print res