1. import os
  2. import time
  3. import threading
  4. def extend_file_logic(filepath, task_function, timeout=5):
  5. """
  6. Executes a task on a file, handling timeouts and errors with defensive checks.
  7. Args:
  8. filepath (str): The path to the file.
  9. task_function (callable): The function to execute on the file.
  10. timeout (int): Timeout in seconds for the task.
  11. Returns:
  12. bool: True if the task completed successfully, False otherwise.
  13. """
  14. if not os.path.exists(filepath):
  15. print(f"Error: File not found at {filepath}")
  16. return False
  17. if not os.access(filepath, os.R_OK):
  18. print(f"Error: File is not readable at {filepath}")
  19. return False
  20. def worker():
  21. try:
  22. start_time = time.time()
  23. result = task_function(filepath)
  24. end_time = time.time()
  25. if (end_time - start_time) > timeout:
  26. print(f"Warning: Task timed out after {timeout} seconds for {filepath}")
  27. return False
  28. return True
  29. except Exception as e:
  30. print(f"Error executing task on {filepath}: {e}")
  31. return False
  32. # Use a thread to avoid blocking the main program
  33. thread = threading.Thread(target=worker)
  34. thread.start()
  35. thread.join(timeout) # Wait for the thread to complete, with timeout
  36. return thread.is_alive() == False # Check if the thread is still running after the timeout
  37. if __name__ == '__main__':
  38. def my_task(filepath):
  39. """Example task: Adds a line to the file."""
  40. try:
  41. with open(filepath, "a") as f:
  42. f.write(f"Task executed at {time.ctime()}\n")
  43. return True
  44. except Exception as e:
  45. print(f"Error in my_task: {e}")
  46. return False
  47. # Example usage:
  48. filepath = "my_file.txt"
  49. if extend_file_logic(filepath, my_task):
  50. print(f"Task completed successfully for {filepath}")
  51. else:
  52. print(f"Task failed or timed out for {filepath}")

Add your comment