2019 年 Python 2/3 Asyncio

Cli*_*ick 3 python python-2.7 python-3.x python-asyncio

我必须同时保持我的应用程序与 Python 2 和 3 兼容。

我有一些如下代码,我希望能够异步调用函数,然后等待所有的 future 得到解决。

代码:

import requests

# This would return a future
def get_xhr(url):
    return requests.get('https://www.{}.com'.format(url))

# This would return an array of futures
def get_search_engines():
    urls = ['google', 'yahoo', 'bing']
    return [get_xhr(url) for url in urls]


# Here I want to wait for all the futures to be resolved
get_search_engines()

print('All requests are done')
Run Code Online (Sandbox Code Playgroud)

Asyncio async/await 似乎只与 Python 3 兼容。

能够运行与 python 2/3 兼容的异步函数的最佳方法是什么?

Mes*_*ssa 5

对于 Python 2,有TwistedTornado

但也许在您的用例中,线程(threading并发.futures)将是最简单的解决方案。

另请记住,Python 2 将在 2019 年底不再维护

  • 请注意,Python 2 上不存在 `concurrent.futures`,但 [向后移植](https://pypi.org/project/futures/) 存在。考虑到这一点,我绝对建议使用“concurrent.futures”(Python 2 中的向后移植)而不是原始“线程”。 (2认同)