Timeout for block of code in Python?
- User
Timeout for block of code in Python?
- Assistant
In Python, implementing a timeout for a block of code isn't straightforward because Python itself doesn't provide a built-in way to apply timeouts directly to arbitrary blocks of code. However, there are several workarounds you can use depending on your specific needs and environment.
Using
signalmodule (Unix only)You can use the
signalmodule to set a timeout for a block of code in Unix-based systems. This approach uses alarms to interrupt code execution if it exceeds the specified time limit.pythonimport signal class TimeoutException(Exception): pass def handler(signum, frame): raise TimeoutException() # Usage example try: # Set the signal handler and an alarm signal.signal(signal.SIGALRM, handler) signal.alarm(5) # Timeout set to 5 seconds # Protected block of code # This example sleeps for 10 seconds, which would trigger the timeout import time time.sleep(10) signal.alarm(0) # Disable the alarm except TimeoutException: print("Timed out!") finally: # Clean up the alarm in every case signal.alarm(0)Using
concurrent.futures.ThreadPoolExecutorYou can run your code in a separate thread using
concurrent.futures.ThreadPoolExecutor, which allows you to specify a timeout for the task.pythonfrom concurrent.futures import ThreadPoolExecutor, as_completed, TimeoutError def my_function(): import time time.sleep(10) # Simulate a long-running task return "Completed" # Set the timeout timeout_seconds = 5 # Use ThreadPoolExecutor for timeout with ThreadPoolExecutor(max_workers=1) as executor: future = executor.submit(my_function) try: result = future.result(timeout=timeout_seconds) print(result) except TimeoutError: print("Timed out!")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.