gpt4 book ai didi

python - 如何捕获并发.futures._base.TimeoutError

转载 作者:行者123 更新时间:2023-12-03 07:28:07 26 4
gpt4 key购买 nike

我正在 try catch run_until_complete 内抛出的异常,但无论我尝试什么,我似乎都无法正确捕获它们。

这是我的最新尝试(注意,我使用的是 Pypputeer,它是 Python 中 Puppeteer 的一个分支,它使用 asyncio):

import asyncio
from pyppeteer.launcher import launch

async def test(instance):
page = await instance.newPage()
await page.goto('http://www.google.com', {'waitUntil': 'load', 'timeout': 1})
await page.pdf({'path': 'example.pdf'})


async def test2():
instance = launch(headless=True)
try:
task = asyncio.ensure_future(test(instance))
print(task)
await task
except:
print("Caught!")

instance.close()


def __main__():
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(test2())
except:
print("ERROR")
return 'ok'

我在这段代码中遇到的问题有两个:

  1. 如果我改为 asyncio.get_event_loop,则会收到以下错误:

There is no current event loop in thread 'Thread-1'.2. If I change the timeout to a decent value, I get the following error (at loop.run_until_complete(test2())):RuntimeError: This event loop is already running3. If I set the timeout to 1 (to force the error), I get the exception indicated below, shown in the console, and the text "ERROR" is shown. (but not caught).

这是堆栈跟踪:

Exception in callback NavigatorWatcher.waitForNavigation.<locals>.watchdog_cb(<Task finishe...> result=None>) at /home/user/www/project/api/env/lib/python3.6/site-packages/pyppeteer/navigator_watcher.py:49
handle: <Handle NavigatorWatcher.waitForNavigation.<locals>.watchdog_cb(<Task finishe...> result=None>) at /home/user/www/project/api/env/lib/python3.6/site-packages/pyppeteer/navigator_watcher.py:49>
Traceback (most recent call last):
File "/usr/lib64/python3.6/asyncio/events.py", line 145, in _run
self._callback(*self._args)
File "/home/user/www/project/api/env/lib/python3.6/site-packages/pyppeteer/navigator_watcher.py", line 52, in watchdog_cb
self._timeout)
File "/home/user/www/project/api/env/lib/python3.6/site-packages/pyppeteer/navigator_watcher.py", line 40, in _raise_error
raise error
concurrent.futures._base.TimeoutError: Navigation Timeout Exceeded: 1 ms exceeded

那么,TLDR,如何捕获 asyncio 的 run_until_complete 调用中抛出的异常?

最佳答案

您无法捕获此错误,因为它不会在事件循环完成工作之前发生在某个地方:

loop.run_until_complete(test2())
print('TEST !!!') # You will see this line, because there was no exception before

但是如果你查看整个回溯,你会看到:

Error in atexit._run_exitfuncs:

这意味着使用atexit注册的Pypputeer函数之一内部发生了异常。处理程序。您应该在那里搜索如何捕获异常,但我不确定是否可能。

If an exception is raised during execution of the exit handlers, a traceback is printed (unless SystemExit is raised) and the exception information is saved. After all exit handlers have had a chance to run the last exception to be raised is re-raised.

<小时/>

不相关,但是never do这样的事情。

except:

关于python - 如何捕获并发.futures._base.TimeoutError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49014284/

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