简体   繁体   中英

Simplest way to gracefully cancel an asyncio job in Python?

I've been playing around with an API, and call a function when a specific string is caught.

At the moment, I'm using sys.exit inside the function to end the script. However that causes an error:

_ClientEventTask exception was never retrieved
future: <ClientEventTask state=finished event=on_message coro=<bound method MyClient.on_message of <__main__.MyClient object at 0x123b20a00>> exception=SystemExit()>

I'd like to shutdown the script gracefully. The relevant code snippet is here:

class MyClient(API.Client):

      async def on_message(self, message):

        if (message.channel.id == XXX): 
            dostuff(message.content)

client = MyClient()

client.run('XXX')

I've tried a number of things and am a little stuck. Would greatly appreciate any help with this, thanks!

A straightforward way to achieve what you want is to replace sys.exit() with asyncio.get_event_loop().stop() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM