Python 中超时中断函数
当调用可能无限期停止的函数时,阻止脚本进一步执行,有必要实施超时机制。 Python 的 signal 包为这个问题提供了解决方案。
signal 包主要用于 UNIX 系统,允许您为特定函数设置超时。如果函数超过指定的超时,则会发出信号以中断执行。
示例:
考虑一个可能无限期运行的函数loop_forever()。我们需要调用此函数,但设置 5 秒的超时。如果函数执行时间超过 5 秒,我们想取消它的执行。
import signal # Register a handler for the timeout def handler(signum, frame): print("Timeout! Cancelling function execution.") raise Exception("Timeout exceeded!") # Register the signal function handler signal.signal(signal.SIGALRM, handler) # Define a timeout of 5 seconds signal.alarm(5) try: loop_forever() except Exception as e: print(str(e)) # Cancel the timer if the function finishes before timeout signal.alarm(0)
在此示例中,5 秒后,调用处理函数,引发异常。该异常在父代码中被捕获,然后取消计时器并终止loop_forever()函数的执行。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3