【问题标题】:Python 2/3 Asyncio in 20192019 年 Python 2/3 Asyncio
【发布时间】:2019-01-13 02:56:48
【问题描述】:

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

我有一些类似下面的代码,我希望能够异步调用一个函数,然后等待我所有的未来都得到解决。

代码:

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 python-3.x python-2.7 python-asyncio


    【解决方案1】:

    对于 Python 2,有 TwistedTornado

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

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

    【讨论】:

    • 请注意,concurrent.futures 在 Python 2 上不存在,但 a backport 存在。考虑到这一点,我绝对建议使用 concurrent.futures(Python 2 中的反向端口)而不是原始 threading
    猜你喜欢
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多