24

我正在尝试使我的 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 })
4

2 回答 2

50

你能用six吗?它的存在就是为了解决这个问题。

import six, sys
six.reraise(*sys.exc_info())

见:https ://six.readthedocs.io/index.html#six.reraise

于 2013-01-24T15:38:26.990 回答
0

You could do something creative.

Have a check at the start of your code - your constructor or whatever, check what version of python you are using, since your normal version checker is not working, try this instead:

try:
  eval('a python 3 expression') # something that only works in python3+
  python_version = 3
except:
  python_version = 2

Then the rest of your code can easily just reference this to know what to use.

As for the parse errors, you can use exec in a function, like so:

def what_to_run():
    if python_version = 3:
        return 'raise exc_info[0].with_traceback(exc_info[1], exc_info[2])'
    else:
        return 'raise exc_info[0], exc_info[1], exc_info[2]'

In your function you would write this:

def start_response(status, response_headers, exc_info = None):
    if exc_info:
        try:
            if headers_sent:
                # Re-raise original exception if headers sent.
                exec(what_to_run())
        finally:
            # Avoid dangling circular ref.
            exc_info = None
    elif headers_set:
        raise AssertionError("Headers already set!")

    headers_set[:] = [status, response_headers]
    return write

A bit messy, untested, but it should work, at least you understand the idea.

于 2013-01-24T14:42:39.927 回答