import os
import time
import threading
def extend_file_logic(filepath, task_function, timeout=5):
"""
Executes a task on a file, handling timeouts and errors with defensive checks.
Args:
filepath (str): The path to the file.
task_function (callable): The function to execute on the file.
timeout (int): Timeout in seconds for the task.
Returns:
bool: True if the task completed successfully, False otherwise.
"""
if not os.path.exists(filepath):
print(f"Error: File not found at {filepath}")
return False
if not os.access(filepath, os.R_OK):
print(f"Error: File is not readable at {filepath}")
return False
def worker():
try:
start_time = time.time()
result = task_function(filepath)
end_time = time.time()
if (end_time - start_time) > timeout:
print(f"Warning: Task timed out after {timeout} seconds for {filepath}")
return False
return True
except Exception as e:
print(f"Error executing task on {filepath}: {e}")
return False
# Use a thread to avoid blocking the main program
thread = threading.Thread(target=worker)
thread.start()
thread.join(timeout) # Wait for the thread to complete, with timeout
return thread.is_alive() == False # Check if the thread is still running after the timeout
if __name__ == '__main__':
def my_task(filepath):
"""Example task: Adds a line to the file."""
try:
with open(filepath, "a") as f:
f.write(f"Task executed at {time.ctime()}\n")
return True
except Exception as e:
print(f"Error in my_task: {e}")
return False
# Example usage:
filepath = "my_file.txt"
if extend_file_logic(filepath, my_task):
print(f"Task completed successfully for {filepath}")
else:
print(f"Task failed or timed out for {filepath}")
Add your comment