首页 > 解决方案 > 取消包装到异步同步功能

问题描述

我有包装到异步的同步函数,但是在异步回调中取消它是一个问题。我试图取消它,但没有成功。这是一种取消它的方法,还是我应该将它用作线程中带有事件循环的同步函数?如果有任何帮助,我将不胜感激。

from telethon import TelegramClient, events, sync
from telethon.sync import TelegramClient
import asyncio
from functools import wraps, partial
from telethon import Button
import requests as r



api_id = ***
api_hash = ***
bot_token = ***
bot = TelegramClient('bot', api_id, api_hash).start(bot_token=bot_token)


@bot.on(events.NewMessage(pattern='/start'))
async def start_handler(event):
    await bot.send_message(event.message.peer_id.user_id, 'Hello!',
                           buttons=[[Button.inline('Add username to blacklist', b'blacklist_add')]])


@bot.on(events.CallbackQuery(data=b'blacklist_add'))
async def add_handler(event):
    await event.answer()
    for task in asyncio.all_tasks():
        if task.get_coro().__name__ == 'man':
            task.cancel()



def wrk():
    resp = r.get('https://www.google.com')
    print(resp.text)


def async_wrap(func):
    @wraps(func)
    async def run(*args, loop=None, executor=None, **kwargs):
        if loop is None:
            loop = asyncio.get_event_loop()
        pfunc = partial(func, *args, **kwargs)
        return await loop.run_in_executor(executor, pfunc)
    return run


@async_wrap
def man():
    try:
        while 1:
            wrk()
    except asyncio.CancelledError:
        print('man')


bot.start(bot_token=bot_token)
loop = asyncio.get_event_loop()
task = loop.create_task(man())
loop.run_until_complete(task)
loop.run_forever()

标签: pythonpython-asyncio

解决方案


推荐阅读