Catgirl21
Catgirl21

Reputation: 37

asyncio: Stop coroutine on exception

I am writing a function that has to be self-restarted in case of catching an exception but I don't know how to do it. I have this piece of code but it doesn't work.:

import asyncio

async def main():
    while True:
        try:
            #REALLY huge amount of code
        except Exception as e:
            print(f"Exception: {e}")
            # Here I want this script to run main() again
            return


asyncio.run(main())

Upvotes: 0

Views: 435

Answers (1)

Keith
Keith

Reputation: 43024

Your main function is a co-routine, and co-routines hold state. Re-starting the same one probably isn't a good idea. You want two functions, the co-routine main, and a regular function main that handles creating a new co-routine and running it again.

async def amain():
    # Lot of code

def main():
    while True:
        try:
            asyncio.run(amain())
        except KeyboardInterrupt:
            break
        except Exception as e:
            log(e)

Something like that.

Upvotes: 1

Related Questions