从 python gevent 输出中删除堆栈跟踪

Remove stacktrace from python gevent output

我是 python 的新手,并试图在引发异常时 remove/trim gevent stacktrace 输出。我在某处读到我可以通过使用 AsyncResult 来实现它,但是我似乎不知道如何使用它。

这是我开始的一个例子,并反复迭代以使其类似于我正在排除故障的真实代码,但是当我尝试将 my_decor 添加到 work() 时,我陷入了最后一个阶段. 非常感谢任何解决此问题的帮助。

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

找到答案了,希望对遇到同样问题的人有所帮助。

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