How to await a coroutine with an event loop

喜夏-厌秋 提交于 2020-05-14 03:28:39

问题


I have a coroutine that has an event loop. How should I await that coroutine? I am using Python 3.7.3.

# The coroutine
async def main():
    #
    # This code written using apscheduler.schedulers.asyncio.AsyncIOScheduler
    # which has its *event loop* to run scheduled tasks
    # 
    # However, this code will await another coroutine, e.g.,
    # redis = await aioredis.create_redis('/tmp/redis.sock')

    try:
        asyncio.get_event_loop().run_forever()
    except:
        pass


if __name__ == '__main__':
    asyncio.run(main())

The code only runs the main event loop created by asyncio.run() but not the one by managed by apscheduler.

Update 1

However, if change the code to

# The coroutine
async def main():
    #
    # This code written using apscheduler.schedulers.asyncio.AsyncIOScheduler
    # which has its *event loop* to run scheduled tasks
    # 
    # However, this code will await another coroutine, e.g.,
    # redis = await aioredis.create_redis('/tmp/redis.sock')

    #try:
    #    asyncio.get_event_loop().run_forever()
    #except:
    #    pass


if __name__ == '__main__':
    asyncio.run(main())

The code runs main() once as the event loop managed by apscheduler does not run.

However, if change the code to

# The coroutine
async def main():
    #
    # This code written using apscheduler.schedulers.asyncio.AsyncIOScheduler
    # which has its *event loop* to run scheduled tasks
    # 
    # However, this code will await another coroutine, e.g.,
    # redis = await aioredis.create_redis('/tmp/redis.sock')

    try:
        asyncio.get_event_loop().run_forever()
    except:
        pass


if __name__ == '__main__':
    main()

The complains that the coroutine 'main' was never awaited.

来源:https://stackoverflow.com/questions/61291928/how-to-await-a-coroutine-with-an-event-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!