Python 3.x 异步IO任务在等待时停止

Python 3.x 异步IO任务在等待时停止,python-3.x,python-asyncio,aiohttp,Python 3.x,Python Asyncio,Aiohttp,我有一个异步函数,其中很少有等待 async def registerit(arg1,arg2): async with aiohttp.ClientSession() as session: url="https://google.com" headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'

我有一个异步函数,其中很少有等待

async def registerit(arg1,arg2):
    async with aiohttp.ClientSession() as session:
        url="https://google.com"
        headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}
        response = await session.get(url, headers=headers)

由于某种原因,代码在等待东西时停止,只有在我使用

task = asyncio.create_task(registerit(arg1,arg2))
tasks.append(task)
如果我使用

await registerit(arg1,arg0)

感谢您的帮助。

我看不到您如何真正运行代码的详细信息,但我猜您没有让您创建的任务(使用
asyncio.create\u task
)轮到它执行

await registerit(arg1,arg0)
有效,因为当您使用
await
时,您会将当前执行上下文切换到另一个协同程序,而该协同程序可能就是您刚刚使用
await
启动的协同程序。wait创建新的协同路由并等待它完成并获得其输出

与等待不同,任务用于并发(后台)工作。请记住,当您创建它时,您只需将它放在协同路由队列中,以便在上下文切换点执行。因此,如果运行
create_task
作为代码的最后一行,将创建与工作的协同程序,并将其放入执行队列,但队列将与程序一起停止

但是,如果您使用
await
将程序的控制权交还给事件循环,并使用
await asyncio.sleep(5)
之类的方法停止程序的结束,则将运行“非工作”代码。或者您可以首先使用
run\u forever()
运行循环

通过运行my test.py,您可以看到:

#test.py
#python 3.8.1
导入异步
进口aiohttp
异步def非工作解决方案():
task=asyncio.create_任务(registerit())
异步def工作_解决方案():
等待注册
异步def注册表项():
与aiohttp.ClientSession()作为会话异步:
url=”https://google.com"
headers={'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
“用户代理”:“Mozilla/5.0(Windows NT 10.0;Win64;x64)AppleWebKit/537.36(KHTML,类似Gecko)Chrome/71.0.3578.98 Safari/537.36”}
response=wait session.get(url,headers=headers)
打印(答复)
异步def main():
打印('正在运行的工作解决方案')
等待工作解决方案()
打印('正在运行的非工作解决方案')
等待非工作解决方案()
#修复
# =======
睡眠时间=5
打印('等待',睡眠时间,'非工作解决方案输出秒')
等待异步睡眠(时间到睡眠)
# =======
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
asyncio.run(main())