我正在尝试使我的 WSGI 服务器实现与 Python 2 和 Python 3 兼容。我有以下代码:
def start_response(status, response_headers, exc_info = None):
if exc_info:
try:
if headers_sent:
# Re-raise original exception if headers sent.
raise exc_info[0], exc_info[1], exc_info[2]
finally:
# Avoid dangling circular ref.
exc_info = None
elif headers_set:
raise AssertionError("Headers already set!")
headers_set[:] = [status, response_headers]
return write
...相关部分是:
# Re-raise original exception if headers sent.
raise exc_info[0], exc_info[1], exc_info[2]
Python 3 不再支持该语法,因此必须将其翻译为:
raise exc_info[0].with_traceback(exc_info[1], exc_info[2])
问题:Python 2 语法在 Python 3 中生成解析错误。如何编写可以被 Python 2 和 Python 3 解析的代码?我尝试了以下方法,但这不起作用:
if sys.version_info[0] >= 3:
raise exc_info[0].with_traceback(exc_info[1], exc_info[2])
else:
eval("raise exc_info[0], exc_info[1], exc_info[2]; 1", None, { 'exc_info': exc_info })