在python中如何在X秒后引发超时异常

2024-06-16 11:35:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,我需要在X秒后引发异常我该怎么做? 我尝试了这个代码,但它不起作用:

from eventlet.timeout import Timeout
timeout = Timeout(seconds, exception)
try:
   do somethins
finally:
   timeout.cancel()

Tags: 函数代码fromimporttimeoutexceptiondocancel
1条回答
网友
1楼 · 发布于 2024-06-16 11:35:58

根据the timeout documentation

There are two Timeout caveats to be aware of:

  • If the code block in the try/finally or with-block never cooperatively yields, the timeout cannot be raised. In Eventlet, this should rarely be a problem, but be aware that you cannot time out CPU-only operations with this class.
  • If the code block catches and doesn't re-raise BaseException (for example, with except:), then it will catch the Timeout exception, and might not abort as intended.

如果在循环中没有执行任何IO/sleep,则不会发生超时。在

相关问题 更多 >