gpt4 book ai didi

python - 有没有办法使用 atexit 运行异步协程?

转载 作者:行者123 更新时间:2023-11-28 18:05:33 24 4
gpt4 key购买 nike

我正在使用 `discord.py 开发一个机器人。该机器人创建/删除多个 channel ,并连接到 SQLite 数据库。如果机器人崩溃了,我希望它能够

  1. 销毁它创建的所有临时语音 channel 。
  2. 断开与 SQL 数据库的连接。

这是关闭协程:

async def shutdown(self):
print("Shutting down Canvas...")
for ch in self.active_channels:
await client.delete_channel(ch)
self.db.close()

我尝试过的事情:

# Canv is the interface between the bot and the data we're collecting
atexit.register(canv.shutdown)
bot.run(TOKEN)

try:
bot.loop.run_until_complete(bot.start(TOKEN))
except KeyboardInterrupt or InterruptedError:
bot.loop.run_until_complete(canv.shutdown())
finally:
bot.loop.close()

from async_generator import asynccontextmanager

@asynccontextmanager
async def cleanup_context_manager():
try:
yield
finally:
await canv.shutdown()

with cleanup_context_manager():
bot.run(TOKEN)

这些都不运行 canv.shutdown(),这是一个 asyncio.coroutine。如何确保此代码在每种 退出类型上运行?

我用了this post获取一些信息,我认为它最接近我想要的。

最佳答案

你可以试试这样的东西

import asyncio
import atexit


@atexit.register
def shutdown(self):
print("Shutting down Canvas...")
loop = asyncio.get_event_loop()
loop.run_until_complete(await_delete_channels())
self.db.close()


async def await_delete_channels(self):
# # Works but it is better to do it asynchronously
# for ch in self.active_channels:
# await client.delete_channel(ch)
#
# Doing delete_channels() asynchronously
delete_channels = [client.delete_channel(ch) for ch in self.active_channels]
await asyncio.wait(delete_channels, return_when=asyncio.ALL_COMPLETED)

关于python - 有没有办法使用 atexit 运行异步协程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53640988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com