【发布时间】:2021-08-20 07:51:06
【问题描述】:
import asyncio
import time
import aiohttp
now = lambda :time.time()
async def do_some_work(x):
print("waiting:",x)
await asyncio.sleep(x)
return f"Web is ok"
start = now()
coroutine = do_some_work(2) # a future
loop = asyncio.get_event_loop()
task = asyncio.ensure_future(coroutine)
loop.run_until_complete(task)
print("In the process of accessing web") # I want this run first before sleep
print("Task ret:", task.result())
print("Time:", now() - start)
这些是我的结果和问题:
- python3 test_aio_return.py
- 等待:2(睡在这里)
- 正在访问网络。
- 任务恢复:
Web is ok。我希望它在这一步休眠,因为我正在使用协程这一行的结果。 - 时间:2.0011699199676514
【问题讨论】:
-
问题是什么?你应该更好地描述问题。
-
如果你想在
sleep()之前运行print(...),那么把它放在loop.run...之前。或者您应该将其作为另一个任务运行。因为run_until_complete阻塞了其他代码until complete tasks -
抱歉,我没有明确提出我的问题。是的,我确实希望我的
print在sleep之前运行,但我想让sleep先运行,然后当协程处于睡眠状态时,该进程将被授予主线程,然后它转到print("In the process of accessing web")和我只是想知道协程在睡眠时会将处理器授予主线程吗? -
当您使用
coroutine时,您还必须在coroutine中运行其他元素 - 因为run_until_complete一直在运行,它无法运行其他代码。
标签: python python-asyncio aiohttp