问题
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