1. import time
  2. import functools
  3. def with_timeout(seconds):
  4. """
  5. Decorator to add a timeout to a function.
  6. """
  7. def decorator(func):
  8. @functools.wraps(func)
  9. def wrapper(*args, **kwargs):
  10. start_time = time.time()
  11. try:
  12. result = func(*args, **kwargs)
  13. except Exception as e:
  14. print(f"Function {func.__name__} raised an exception: {e}")
  15. raise
  16. elapsed_time = time.time() - start_time
  17. if elapsed_time > seconds:
  18. print(f"Function {func.__name__} timed out after {seconds} seconds.")
  19. raise TimeoutError(f"Function {func.__name__} timed out after {seconds} seconds.")
  20. return result
  21. return wrapper
  22. return decorator
  23. class TimeoutError(Exception):
  24. """Custom exception for timeout scenarios."""
  25. pass

Add your comment