如何在 gevent 中捕获回溯
我生成了一个 Greenlet 并将其链接到一个可调用对象。一段时间后,Greenlet 因异常而失败。链接的可调用对象被调用。太棒了!
问题是这样的:
正如您所期望的,异常的回溯出现在我的控制台上。但我想在链接的可调用对象中使用回溯进行操作。如何访问链接的可调用对象中的回溯?
(我的第一反应是使用traceback.extract_stack(),但事实证明它为链接的可调用本身提供了回溯,而不是为异常提供了回溯。)
I've spawned a Greenlet and linked it to a callable. Some time later, the Greenlet fails with an Exception. The linked callable gets called. That's all great!
Here's the issue:
The traceback for the Exception appears on my console, as you'd expect. But I want do things with that traceback within the linked callable. How do I get access to that traceback within the linked callable?
(My first instinct was to use traceback.extract_stack()
, but it turns out that provides a traceback for the linked callable itself and not for the Exception.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当 Greenlet 死亡时,特意不保存回溯。如果它被保存,它将使许多预计将被删除的对象保持活动状态,这在对象管理某些资源(打开文件或套接字)时尤其重要。
如果你想保存回溯,你必须自己做。
The traceback is intentionally not saved when the Greenlet dies. If it was saved, it would keep a lot of objects alive that are expected to be deleted, which matters especially if the object manages some resource (open file or socket).
If you want to save the traceback you have to do it yourself.
作为使用
Greenlet.link_exception
的 Stephen Diehl 解决方案的替代方案。As an alternative to Stephen Diehl's solution using
Greenlet.link_exception
.Greenlet
对象应该有一个exception
属性,您可以查看该属性:http://www.gevent.org/gevent.html#gevent.Greenlet.exception
The
Greenlet
object should have anexception
property that you can look at:http://www.gevent.org/gevent.html#gevent.Greenlet.exception
只需确保获取 Greenlet 的
Exception
值并将其扔到 Greenlet 之外,例如get
返回返回的值或引发内部异常。应该给你你需要的东西。
Just make sure you grab the
exception
value of the Greenlet and throw it outside the Greenlet, for exampleget
returns either the value returned or raises the internal exception.Should give you what you need.