原始回溯的例外 - 2.6-3.X 兼容版本 [英] Exception with original traceback - 2.6-3.X compatible version

查看:42
本文介绍了原始回溯的例外 - 2.6-3.X 兼容版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的上下文管理器 - 它在 Python 2.X 中工作并在退出时保留回溯.

Say I have a context manager like this - which works in Python 2.X and preserves traceback on exit.

class MyContextManager(object):
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_value, traceback):
        raise AssertionError("Failed :-/"), None, traceback

在 Python 3 中,raise 是一个语法错误,但我认为您可以设置 __traceback__ 参数.

In Python 3, the raise is a syntax error, but I think you can just set the __traceback__ parameter.

def __exit__(self, exc_type, exc_value, traceback):
    e = AssertionError("Failed :-/")
    e.__traceback__ = traceback
    raise e

有没有办法保留与 Python 2 和 Python 3 兼容的回溯(即,两者都不会产生语法错误)?我在这一点上有些卡住了.它需要在 2.6、2.7、3.2 和 3.3 中工作.目标是确保用户仍能看到较早的回溯.

Is there a way to preserve traceback that's compatible with both Python 2 and Python 3 (i.e., doesn't generate syntax errors on either)? I'm somewhat stuck at this point. It needs to work in 2.6, 2.7, 3.2 and 3.3. The goal would be to make sure that the user still sees the earlier traceback.

推荐答案

我想到的一个丑陋但可行的答案(灵感来自 Ned Batchelder 的 Python 3 兼容性指南) 是编写一个函数来评估破坏语法的代码,仅当它是 Python 2 时.例如:

One ugly, but workable answer that occurred to me (inspired by Ned Batchelder's guide to Python 3 compatibility) is to write a function to evaluate the syntax-breaking code only if it's Python 2. e.g.:

if sys.version_info[0] == 2:
   s = """
def raise_with_traceback(exc, traceback):
    raise exc, None, traceback
"""
   exec (s)
else:
   def raise_with_traceback(exc, traceback):
       raise exc.with_traceback(traceback)

[给@user2357112 的提示,关于 with_traceback 是 Python 3 的首选].

[hat tip to @user2357112 about with_traceback being preferred for Python 3].

这篇关于原始回溯的例外 - 2.6-3.X 兼容版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆