【问题标题】:Asyncio tasks stopping on await [closed]Asyncio 任务在等待时停止 [关闭]
【发布时间】:2020-01-13 21:23:50
【问题描述】:

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

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)

感谢您的帮助。

【问题讨论】:

    标签: python-3.x python-asyncio aiohttp


    【解决方案1】:

    我没有看到您如何真正运行代码的详细信息,但我猜您并没有让您创建的任务(使用asyncio.create_task)轮到执行。

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

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

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

    你可以通过运行我的 test.py 看到:

    # test.py
    # python 3.8.1
    
    import asyncio
    import aiohttp
    
    
    async def non_working_solution():
        task = asyncio.create_task(registerit())
    
    
    async def working_solution():
        await registerit()
    
    
    async def registerit():
        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)
            print(response)
    
    
    async def main():
        print('Running working solution')
        await working_solution()
        print('Running NON-working solution')
        await non_working_solution()
    
        # THE FIX
        # =======
        time_to_sleep = 5
        print('Waiting for', time_to_sleep, 'seconds for the output of the non-working solution')
        await asyncio.sleep(time_to_sleep)
        # =======
    
    
    if __name__ == '__main__':
        asyncio.run(main())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-20
      • 2017-01-22
      • 2014-03-27
      • 2021-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多