2019 年的 Python 2/3 异步

标签 python python-3.x python-2.7 python-asyncio

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

我有一些类似下面的代码,我希望能够异步调用一个函数,然后等待我所有的 futures 被解析。

代码:

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

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

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

最佳答案

对于 Python 2,有 TwistedTornado .

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

另请记住,Python 2 将在 2019 年底停止维护

关于2019 年的 Python 2/3 异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54165742/

相关文章:

python - Tensorflow:提要字典错误:您必须为占位符张量提供一个值

python - 反转 Python 字符串中的单词(包括标点符号)

python - 在Python中将嵌套数组转换为pandas数据框

python - BaseHTTPServer,仅在我的变量发布后接收

python - 使用动态值翻译模板中的字符串

python - 如何使用python中的图形库在窗口上绘制网格

python - 这些集合操作是什么,为什么它们会给出不同的结果?

python - 使用一次后禁用 KeyboardInterrupt

django - 使用 Django ORM 连接两个表之间的记录

python - 尝试在下载的 Cython 目录中安装 Cython : no setup. py