Error asyncio task exception was never retrieved

Context: Playwright Version: 1.19.0 Operating System: Mac Python version: 3.9 Browser: Chromium Code Snippet import asyncio import logging from playwright.async_api import async_playwright, Route, ...

Context:

  • Playwright Version: 1.19.0
  • Operating System: Mac
  • Python version: 3.9
  • Browser: Chromium

Code Snippet

import asyncio
import logging

from playwright.async_api import async_playwright, Route, Error as PlaywrightApiError


async def on_request(route: Route):
    # simulate some time-consuming operations
    await asyncio.sleep(0.5)
    await route.continue_()


async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()

        for _ in range(2):
            page = await browser.new_page()
            page.set_default_timeout(500)
            await page.route("**/*", on_request)
            try:
                await page.goto("https://playwright.dev")
            except PlaywrightApiError as exc:
                logging.error(f"exc: {exc}")
            finally:
                await page.close()

        await asyncio.sleep(1)

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    asyncio.run(main(), debug=True)

OUTPUT:

...
ERROR:asyncio:Task exception was never retrieved
future: <Task finished name='Task-8' coro=<Channel.send() done, defined at /Users/x/PycharmProjects/playwright-python/playwright/_impl/_connection.py:38> exception=Error('Target page, context or browser has been closed') created at /usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/tasks.py:361>
source_traceback: Object created at (most recent call last):
  File "/Users/x/Library/Application Support/JetBrains/PyCharmCE2021.3/scratches/scratch.py", line 32, in <module>
    asyncio.run(main(), debug=True)
  File "/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 629, in run_until_complete
    self.run_forever()
  File "/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 596, in run_forever
    self._run_once()
  File "/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 1882, in _run_once
    handle._run()
  File "/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "/Users/x/Library/Application Support/JetBrains/PyCharmCE2021.3/scratches/scratch.py", line 10, in on_request
    await route.continue_()
  File "/Users/x/PycharmProjects/playwright-python/playwright/async_api/_generated.py", line 762, in continue_
    await self._async(
  File "/Users/x/PycharmProjects/playwright-python/playwright/_impl/_network.py", line 269, in continue_
    await self._race_with_page_close(
  File "/Users/x/PycharmProjects/playwright-python/playwright/_impl/_network.py", line 289, in _race_with_page_close
    [asyncio.create_task(future), page._closed_or_crashed_future],
  File "/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/tasks.py", line 361, in create_task
    task = loop.create_task(coro)
Traceback (most recent call last):
  File "/Users/x/PycharmProjects/playwright-python/playwright/_impl/_connection.py", line 39, in send
    return await self.inner_send(method, params, False)
  File "/Users/x/PycharmProjects/playwright-python/playwright/_impl/_connection.py", line 63, in inner_send
    result = next(iter(done)).result()
playwright._impl._api_types.Error: Target page, context or browser has been closed
INFO:asyncio:<_UnixReadPipeTransport fd=8 polling> was closed by peer
DEBUG:asyncio:process 98057 exited with returncode 0
INFO:asyncio:<_UnixSubprocessTransport pid=98057 running stdin=<_UnixWritePipeTransport closed fd=7 closed> stdout=<_UnixReadPipeTransport closed fd=8 closed>> exited with return code 0
DEBUG:asyncio:Close <_UnixSelectorEventLoop running=False closed=False debug=True>
...

Describe the bug

with a long-running browser, after page created, hook the route of page. and do some operation long than timeout, and will see some error log print.
maybe bug is at here. fut task is created but without any exception handler.

async def _race_with_page_close(self, future: Coroutine) -> None:
if hasattr(self.request.frame, «_page»):
page = self.request.frame._page
# When page closes or crashes, we catch any potential rejects from this Route.
# Note that page could be missing when routing popup’s initial request that
# does not have a Page initialized just yet.
await asyncio.wait(
[asyncio.create_task(future), page._closed_or_crashed_future],
return_when=asyncio.FIRST_COMPLETED,
)

POC to fix

    async def _race_with_page_close(self, future: Coroutine) -> None:
        if hasattr(self.request.frame, "_page"):
            page = self.request.frame._page
            # When page closes or crashes, we catch any potential rejects from this Route.
            # Note that page could be missing when routing popup's initial request that
            # does not have a Page initialized just yet.
            fut = asyncio.create_task(future)
            await asyncio.wait(
                [fut, page._closed_or_crashed_future],
                return_when=asyncio.FIRST_COMPLETED,
            )
            if page._closed_or_crashed_future.done():
                await asyncio.gather(fut, return_exceptions=True)
        else:
            await future

Содержание

  1. Aiogram Message is not modified как исправить?
  2. Телеграм бот на aiogram выдает ошибку?
  3. Как исправить asyncio:Task exception was never retrieved?
  4. DateTimeField serialization error on Windows 10 #349
  5. Comments
  6. Context
  7. Expected Behavior
  8. Current Behavior
  9. Failure Information (for bugs)
  10. Steps to Reproduce
  11. Failure Logs
  12. Context
  13. Sys info
  14. MRE (just an echo bot):
  15. Steps to reproduce:
  16. Developing with asyncio¶
  17. Debug Mode¶
  18. Concurrency and Multithreading¶
  19. Running Blocking Code¶
  20. Logging¶

Aiogram Message is not modified как исправить?

Пишу простого бота для телеграмма, выходит ошибка:

  • Вопрос задан 24 нояб. 2022
  • 207 просмотров

Средний 6 комментариев

Вы пытаетесь в цикле поменять текст сообщения на тот же самый текст.
Протокол телеграмма не позволяет этого делать, потому что это бессмысленно.
Вы можете:
1) помнить предыдущий текст и сравнивать новый с ним, чтобы вызыватьредактирование только если текст изменился.
2) Перехватывать и игнорировать MessageNotModified, если считаете, что эта ситуация будет редкой и лишний трафик на сервера телеги вас не беспокоят.
3) Вы можете чисто логически не редактировать сообение, если исходные параметры его не поменялись.
4) вы можете гарантированно менять исходные параметры сообщения, чтобы оно гарантированно изменило текст.

Выбирайте решение на своё усмотрение. А в той второй ошибке, что вы привели в комментах, вы не учитываете, что счетчик у вас глобальный на уровне модуля и достуен во всех функциях модуля, но если вы делаете его присвоение в коде функции, то в ней появляется локальная одноименная переменная, которая перекрывает глобальную, но в конкретно этом случае вызывает ошибку, поскольку при первой итерации у вас локальная переменная еще не определена, хотя фактически объявлена.
Вам нужно почитать как в питоне работают неймспейсы, как объявлять переменные в функции из глобального скоупа.

temjiu, видно что новичок. Просто перехватывайте и игнорируйте ошибку для начала.

На самом деле никакой БД не требуется, а помнить надо столько элементов, сколько сообщений с ценой у вас должно обновляться редактированием.
В вашем коде достаточно сохранить в отдельной локальной переменной отосланный перед циклом текст, а потом перед каждым редактированием сравнивать значение это йперемнной с вновь сгенерированным текстом. Если отличий нет, то редактировать не надо, если есть, то редактируем и перезаписываем новый текст в переменную.

Интереснее будет, если вам надо, чтобы при перезапуске бот не создавал новое сообщение, а редактировал одно из последних. Тогда первое значение можно вычитать из сообщение, или первое редактирование сделать в любом случае, но проигнорировав ошибку. При следующих редактированиях лучше всё же до ошибки не доводить. То есть не делать попытку редактирования. если текст не изменился. Это сэкономит вызовы к АПИ телеги и повысит производительность кода немного.

Не знаю поймёте ли что я тут написал, но попробуйте.

Источник

Телеграм бот на aiogram выдает ошибку?

Каждый раз выдает одну и ту же ошибку после того, как дело доходит до функций kartoxa и grecha

Task exception was never retrieved
future: exception=TypeError(«to_python() missing 1 required positional argument: ‘self’»)>
Traceback (most recent call last):
File «C:UsersДаняAppDataLocalProgramsPythonPython38libsite-packagesaiogramdispatcherdispatcher.py», line 388, in _process_polling_updates
for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
File «C:UsersДаняAppDataLocalProgramsPythonPython38libsite-packagesaiogramdispatcherdispatcher.py», line 225, in process_updates
return await asyncio.gather(*tasks)
File «C:UsersДаняAppDataLocalProgramsPythonPython38libsite-packagesaiogramdispatcherhandler.py», line 117, in notify
response = await handler_obj.handler(*args, **partial_data)
File «C:UsersДаняAppDataLocalProgramsPythonPython38libsite-packagesaiogramdispatcherdispatcher.py», line 246, in process_update
return await self.message_handlers.notify(update.message)
File «C:UsersДаняAppDataLocalProgramsPythonPython38libsite-packagesaiogramdispatcherhandler.py», line 117, in notify
response = await handler_obj.handler(*args, **partial_data)
File «C:UsersДаняbotmain.py», line 33, in kartoxa
await msg.answer(«Уважаю»,reply_markup=ReplyKeyboardRemove),
File «C:UsersДаняAppDataLocalProgramsPythonPython38libsite-packagesaiogramtypesmessage.py», line 339, in answer
return await self.bot.send_message(
File «C:UsersДаняAppDataLocalProgramsPythonPython38libsite-packagesaiogrambotbot.py», line 312, in send_message
reply_markup = prepare_arg(reply_markup)
File «C:UsersДаняAppDataLocalProgramsPythonPython38libsite-packagesaiogramutilspayload.py», line 56, in prepare_arg
return json.dumps(_normalize(value))
File «C:UsersДаняAppDataLocalProgramsPythonPython38libsite-packagesaiogramutilspayload.py», line 42, in _normalize
return obj.to_python()
TypeError: to_python() missing 1 required positional argument: ‘self’

main.py:
import asyncio

from aiogram.types import ReplyKeyboardMarkup, KeyboardButton
from aiogram.types import ReplyKeyboardRemove
from aiogram import Bot, Dispatcher, executor, types
from config import BOT_TOKEN

loop = asyncio.get_event_loop()
bot = Bot(token=BOT_TOKEN,parse_mode=»HTML»)
dp = Dispatcher(bot,loop=loop)

menu=ReplyKeyboardMarkup(
keyboard=[
[KeyboardButton(text=»картоха»),
KeyboardButton(text=»гречка»)],

Источник

Как исправить asyncio:Task exception was never retrieved?

INFO:aiogram:Bot: Dgonni_Silverhend [@Dgonni_Silverhend_bot]
WARNING:aiogram:Updates were skipped successfully.
INFO:aiogram.dispatcher.dispatcher:Start polling.
ERROR:asyncio:Task exception was never retrieved
future: exception=MessageToDeleteNotFound(‘Message to delete not found’)>
Traceback (most recent call last):
File «G:Gameslibsite-packagesaiogramdispatcherdispatcher.py», line 415, in _process_polling_updates
for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
File «G:Gameslibsite-packagesaiogramdispatcherdispatcher.py», line 235, in process_updates
return await asyncio.gather(*tasks)
File «G:Gameslibsite-packagesaiogramdispatcherhandler.py», line 116, in notify
response = await handler_obj.handler(*args, **partial_data)
File «G:Gameslibsite-packagesaiogramdispatcherdispatcher.py», line 256, in process_update
return await self.message_handlers.notify(update.message)
File «G:Gameslibsite-packagesaiogramdispatcherhandler.py», line 116, in notify
response = await handler_obj.handler(*args, **partial_data)
File «C:UsersbaxarPycharmProjectspythonProject1main.py», line 23, in commands_ban
await message.bot.delete_message(chat_id=auth_data.GROUP_ID, message_id=message.reply_to_message.message_id)
File «G:Gameslibsite-packagesaiogrambotbot.py», line 2950, in delete_message
return await self.request(api.Methods.DELETE_MESSAGE, payload)
File «G:Gameslibsite-packagesaiogrambotbase.py», line 236, in request
return await api.make_request(await self.get_session(), self.server, self.__token, method, data, files,
File «G:Gameslibsite-packagesaiogrambotapi.py», line 140, in make_request
return check_result(method, response.content_type, response.status, await response.text())
File «G:Gameslibsite-packagesaiogrambotapi.py», line 115, in check_result
exceptions.BadRequest.detect(description)
File «G:Gameslibsite-packagesaiogramutilsexceptions.py», line 140, in detect
raise err(cls.text or description)
aiogram.utils.exceptions.MessageToDeleteNotFound: Message to delete not found
Вот ошибка кода

Вот сам код:import auth_data
import logging
from aiogram import Bot, Dispatcher, executor, types
import filters
from filters import IsAdminFilter

# logging level
logging.basicConfig(level=logging.INFO)

# Bot init
bot = Bot(token=auth_data.token)
dp = Dispatcher(bot)

@dp.message_handler(is_admin=True, commands=[‘ban’], commands_prefix=’!/’)
async def commands_ban(message: types.Message):
if not message.reply_to_message:
await message.reply(‘Эта команда должна быть ответом на сообщение ‘)
return

await message.bot.delete_message(chat_id=auth_data.GROUP_ID, message_id=message.reply_to_message.message_id)
await message.bot.kick_chat_member(chat_id=auth_data.GROUP_ID, user_id=message.reply_to_message.from_user.id)

await message.reply_to_message.reply(‘Этот пользовватель забанен’)

@dp.message_handler(content_types=[‘new_chat_members’])
async def chat_members(message: types.Message):
await message.delete()

@dp.message_handler()
async def filter_message(message: types.Message):
if «дебил» in message.text:
await message.delete()

Сам pycharm не пишет что есть какая либо ошибка , но при запуске скрипта уже в телеграмме ошибка происходит

Источник

DateTimeField serialization error on Windows 10 #349

Context

Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.

  • Operating System: Windows 10
  • Python Version: 3.8.0
  • aiogram version: 2.8
  • aiohttp version: 3.6.2
  • uvloop version (if installed): not installed

Expected Behavior

Current Behavior

OSError: [Errno 22] Invalid argument

Failure Information (for bugs)

When datetime is datetime.datetime(1970, 1, 1) the serialization on Windows 10 fails with OSError

Steps to Reproduce

Please provide detailed steps for reproducing the issue.

  1. await bot.kick_user(chat_id, user_id)
  2. print(await bot.get_chat_member(chat_id, user_id))
  3. you get it. no, you

Failure Logs

I would fix it like that:

but I’m not sure if it is normal, doesn’t seem to be ok to me xD

The text was updated successfully, but these errors were encountered:

Is it still reproducible?

Operating System: Windows 10
Python Version: 3.8.5
aiogram version: 2.11.2
aiohttp version: 3.7.3
uvloop version (if installed): not installed

Yep, what just happened with this code:

Context

I would fix it like that:

but I’m not sure if it is normal, doesn’t seem to be ok to me xD

It’s great works! But I’m not sure if it is normal, doesn’t seem to be ok to me xDD

it is only on windows?

The issue still persists on the most recent Aiogram version.

Sys info

OS: Windows 10 Pro for Workstations, build 19044.1889
python: 3.7.0
aiogram: 2.22.1
aiohttp: 3.8.0

MRE (just an echo bot):

Steps to reproduce:

  1. start the bot with the code above
  2. send a random msg to the bot (to see that it’s working)
  3. stop the bot from TG client
  4. receive a long traceback (attached below) from the dispatcher

The bot does not react to any subsequent actions, including pressing «Restart the bot» in TG client.
Only code re-run helps to fix it (the user has to restart the bot before you re-run the code, otherwise — the same error).

Источник

Developing with asyncio¶

Asynchronous programming is different from classic “sequential” programming.

This page lists common mistakes and traps and explains how to avoid them.

Debug Mode¶

By default asyncio runs in production mode. In order to ease the development asyncio has a debug mode.

There are several ways to enable asyncio debug mode:

Setting the PYTHONASYNCIODEBUG environment variable to 1 .

Passing debug=True to asyncio.run() .

In addition to enabling the debug mode, consider also:

setting the log level of the asyncio logger to logging.DEBUG , for example the following snippet of code can be run at startup of the application:

configuring the warnings module to display ResourceWarning warnings. One way of doing that is by using the -W default command line option.

When the debug mode is enabled:

asyncio checks for coroutines that were not awaited and logs them; this mitigates the “forgotten await” pitfall.

Many non-threadsafe asyncio APIs (such as loop.call_soon() and loop.call_at() methods) raise an exception if they are called from a wrong thread.

The execution time of the I/O selector is logged if it takes too long to perform an I/O operation.

Callbacks taking longer than 100 milliseconds are logged. The loop.slow_callback_duration attribute can be used to set the minimum execution duration in seconds that is considered “slow”.

Concurrency and Multithreading¶

An event loop runs in a thread (typically the main thread) and executes all callbacks and Tasks in its thread. While a Task is running in the event loop, no other Tasks can run in the same thread. When a Task executes an await expression, the running Task gets suspended, and the event loop executes the next Task.

To schedule a callback from another OS thread, the loop.call_soon_threadsafe() method should be used. Example:

Almost all asyncio objects are not thread safe, which is typically not a problem unless there is code that works with them from outside of a Task or a callback. If there’s a need for such code to call a low-level asyncio API, the loop.call_soon_threadsafe() method should be used, e.g.:

To schedule a coroutine object from a different OS thread, the run_coroutine_threadsafe() function should be used. It returns a concurrent.futures.Future to access the result:

To handle signals and to execute subprocesses, the event loop must be run in the main thread.

The loop.run_in_executor() method can be used with a concurrent.futures.ThreadPoolExecutor to execute blocking code in a different OS thread without blocking the OS thread that the event loop runs in.

There is currently no way to schedule coroutines or callbacks directly from a different process (such as one started with multiprocessing ). The Event Loop Methods section lists APIs that can read from pipes and watch file descriptors without blocking the event loop. In addition, asyncio’s Subprocess APIs provide a way to start a process and communicate with it from the event loop. Lastly, the aforementioned loop.run_in_executor() method can also be used with a concurrent.futures.ProcessPoolExecutor to execute code in a different process.

Running Blocking Code¶

Blocking (CPU-bound) code should not be called directly. For example, if a function performs a CPU-intensive calculation for 1 second, all concurrent asyncio Tasks and IO operations would be delayed by 1 second.

An executor can be used to run a task in a different thread or even in a different process to avoid blocking the OS thread with the event loop. See the loop.run_in_executor() method for more details.

Logging¶

asyncio uses the logging module and all logging is performed via the «asyncio» logger.

The default log level is logging.INFO , which can be easily adjusted:

Network logging can block the event loop. It is recommended to use a separate thread for handling logs or use non-blocking IO. For example, see Dealing with handlers that block .

Источник

Issue

Lets assume I have a simple code:

import asyncio


async def exc():
    print(1 / 0)


loop = asyncio.get_event_loop()

loop.create_task(exc())

try:
    loop.run_forever()
except KeyboardInterrupt:
    loop.stop()
    loop.close()

If I run it, I get error message immediately

Task exception was never retrieved
future: <Task finished coro=<exc() done, defined at qq.py:4> exception=ZeroDivisionError('division by zero',)>
Traceback (most recent call last):
  File "qq.py", line 5, in exc
    print(1 / 0)
ZeroDivisionError: division by zero

But, if I change loop.create_task(exc()) to task = loop.create_task(exc())

I’ll get the same error message after click ctrl+c

Why does task assignment change the time of output of error?

Solution

A Exception in the Task (of underlying asyncio.Future to be precise) can be retrieved with Future.exception(). If it’s not retrieved, the exception will be handled at release of the Future object with eventloop’s call_exception_handler.

So, as @dirn pointed, while the Task has reference (assigned to variable in your case) it’s not going be freed, therefore del task_future won’t be called, loop’s handler won’t be executed either.

Answered By — kwarunek

Понравилась статья? Поделить с друзьями:
  • Error assignment to expression with array type си
  • Error bgi graphics not supported under windows
  • Error assignment to cast is illegal lvalue casts are not supported
  • Error bfloatpointrendertarget 1 is not set in skyrimprefs ini что делать
  • Error assignment of read only location