我试图使我的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])

问题:Python2语法在Python3中生成了一个解析错误.如何编写可以被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 })

推荐答案

你可以做些有创意的事.

在你的代码开始时判断一下——你的构造函数或者其他什么,判断一下你使用的python版本,因为你的普通版本判断程序不起作用,所以试试以下方法:

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

那么剩下的代码就可以很容易地引用它来知道该使用什么了.

至于解析错误,可以在函数中使用exec,如下所示:

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]'

在你的函数中,你可以这样写:

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

有点混乱,未经测试,但它should个工作,至少你理解的 idea .

Python-3.x相关问答推荐

替换Pandas中组下的列值

小部件padx和包方法ipadx有什么不同?

类变量的Python子类被视为类方法

避免重复连续字符但不包括一个特定字符的正则表达式

在字符串中查找正则表达式的所有模式

Python多进程:运行一个类的多个实例,将所有子进程保留在内存中

Python BeautifulSoup:在 Select 语句中排除其他标签

如何将虚拟变量列转换为多列?

Python - 使用 OpenCV 将字节图像转换为 NumPy 数组

内部如何使用 Python 语法?

二进制文件的 Python 3 和 base64 编码

是否有与 Laravel 4 等效的 python?

如何使 Python3 成为 Geany 中的默认 Python

try 注释散列变量时,ABCMeta对象不可下标

如何获得 BeautifulSoup 标签的所有直接子代?

为什么在 Python 3 中实例的 __dict__ 的大小要小得多?

连接 dict 值,它们是列表

如何为 Python 3.x 安装 psycopg2?

如何在 Pandas 中的超 Big Data 框上创建数据透视表

如何使用 python http.server 运行 CGI hello world