[英]how to raise a timeout exception after X seconds in python
I have a function and I need to raise exception after X seconds how can I do this? 我有一个函数,我需要在X秒后引发异常,我该怎么办? I try this code but It doesen't work:
我尝试了这段代码,但没有用:
from eventlet.timeout import Timeout
timeout = Timeout(seconds, exception)
try:
do somethins
finally:
timeout.cancel()
According to 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.
如果try / finally或with块中的代码块从不协作产生,则无法提高超时时间。 In Eventlet, this should rarely be a problem, but be aware that you cannot time out CPU-only operations with this class.
在Eventlet中,这应该很少有问题,但是请注意,使用此类不能使仅CPU的操作超时。
- 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.
如果代码块捕获了并且没有重新引发BaseException(例如,带有except :),那么它将捕获Timeout异常,并且可能不会按预期中止。
If you are doing expensive calculation without doing any IO/ sleep in a loop, timeout will not occur. 如果您不进行任何IO / 休眠就执行昂贵的计算,则不会发生超时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.