【发布时间】:2019-06-05 19:16:22
【问题描述】:
我正在尝试使用 asyncio lib 尝试让我的代码“同时”发出 3 个 HTTP GET/POST 请求,以便尽快获得响应。 (有时一个或另一个请求会延迟,最终会延迟下一个请求。)
所以我去了 asyncio docs,发现了这个例子:https://docs.python.org/3/library/asyncio-task.html#coroutines
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
print(f"started at {time.strftime('%X')}")
await say_after(1, 'hello')
await say_after(2, 'world')
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
我实际上是为自己适应的,但它似乎没有任何帮助,只是让代码更复杂而没有任何好处。
在测试示例代码时(上图)我假设如果我增加第一个 say_after() 的延迟时间,第二个将首先打印:
await say_after(5, 'hello') #5 seconds of sleep before print
await say_after(2, 'world')
然而,它没有。回报是:
16:04:30 开始
你好
世界
16:04:37结束
那么这个 asyncio 代码的目的是什么?我可以在没有 async 的情况下得到相同的结果:
def say_after_b(delay, what):
time.sleep(delay)
print(what)
def main_b():
print(f"started at {time.strftime('%X')}")
say_after_b(5, 'hello')
say_after_b(2, 'world')
print(f"finished at {time.strftime('%X')}")
main_b()
返回:
16:04:37 开始
你好
世界
16:04:44 结束
在我看来,随着时间的增加,异步代码应该是这样的:
sleep 1 sec > sleep 2 sec > print('world') > sleep 3 sec > sleep 4 sec > sleep 5 sec > print('hello') > End.
我的假设错了吗?
【问题讨论】:
标签: python-3.x asynchronous async-await python-asyncio