python - 取消包装到异步同步功能
问题描述
我有包装到异步的同步函数,但是在异步回调中取消它是一个问题。我试图取消它,但没有成功。这是一种取消它的方法,还是我应该将它用作线程中带有事件循环的同步函数?如果有任何帮助,我将不胜感激。
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()
解决方案
推荐阅读
- windows - 在 Windows 上使用 React Native 运行 Android Studio 模拟器失败
- azure - 自动将用户分配给应用程序中的特定应用程序角色
- java - 使用 CacheJdbcPojoStoreFactory 加载缓存时出现异常
- bixby - 如何将 Javascript 对象传递给 Bixby 的操作输出?
- html - 如何垂直对齐具有不同高度的网格元素?
- python - 使用 Regex 和 Pandas 格式化问题
- vhdl - VHDL - 带复位的推断锁存器 - FSM
- angular - 如何 *ngFor 循环通过 Angular 7/Ionic 4 中的两列?
- sql - 优化时间序列数据的 MIN / MAX 查询
- python - 导入 numpy c-extensions 失败