How to resolve timeout error when using timeout in Python?

Common errors when using a timeout in Python often arise from timeout exceptions, which can be resolved by catching and handling the exception. Here is an example code:

import time
import signal

class TimeoutError(Exception):
    pass

def timeout_handler(signum, frame):
    raise TimeoutError("Timeout")

def do_something():
    time.sleep(10)  # 模拟一个耗时操作

# 设置超时时间为5秒
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(5)

try:
    do_something()
except TimeoutError as e:
    print("操作超时:", e)
finally:
    signal.alarm(0)  # 取消超时设置

In the example above, we set a timeout using the signal module and define a TimeoutError exception to indicate when a timeout occurs. Inside the try block, we perform our operations and catch the TimeoutError exception if a timeout occurs, then output a message before canceling the timeout. This method helps avoid errors when using timeouts in Python.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds