Timeout for block of code in Python?
- User
Timeout for block of code in Python?
- Assistant
In Python, you can implement a timeout for a block of code in several ways. Below are a few common methods:
1. Using
signal(Unix-based systems only)The
signalmodule can be used to raise an exception if a block of code takes too long to execute. Note that this method works only on Unix-like systems and will not work on Windows.pythonimport signal class TimeoutException(Exception): pass def timeout_handler(signum, frame): raise TimeoutException() # Set the signal handler signal.signal(signal.SIGALRM, timeout_handler) def run_with_timeout(seconds, func, *args, **kwargs): # Start the timer signal.alarm(seconds) try: return func(*args, **kwargs) except TimeoutException: print("Timeout occurred!") finally: # Disable the alarm signal.alarm(0) # Example usage def my_function(): # Simulate a long-running task import time time.sleep(10) # Change this to any long-running operation result = run_with_timeout(5, my_function) # Timeout after 5 seconds2. Using
concurrent.futuresconcurrent.futurescan be used with a thread or process pool to run a function with a timeout.pythonfrom concurrent.futures import ThreadPoolExecutor, TimeoutError def my_function(): import time time.sleep(10) # Simulate a long-running task def run_with_timeout(seconds): with ThreadPoolExecutor() as executor: future = executor.submit(my_function) try: result = future.result(timeout=seconds) return result except TimeoutError: print("Timeout occurred!") # Example usage result = run_with_timeout(5) # Timeout after 5 seconds
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.