To interrupt a file reading operation, you can use threading and a stop flag to signal the cancellation. Here's an updated version of your code that integrates this functionality:
import threading
import cv2
import time
import tkinter as tk
stop_flag = False
def start_reading(path):
global stop_flag
stop_flag = False
thread = threading.Thread(target=read_tiff, args=(path,))
thread.start()
def read_tiff(path):
global stop_flag
start = time.time()
print('Start reading\n')
# Read the file in chunks to allow interruption
with open(path, 'rb') as file:
while True:
if stop_flag:
print('Reading cancelled')
break
chunk = file.read(1024)
if not chunk:
break
# Process the chunk
# Example: print(len(chunk))
print('Read finished: %.3f' % (time.time() - start))
def stop_reading():
global stop_flag
stop_flag = True
file = 'random.tiff'
root = tk.Tk()
start_button = tk.Button(root, text="Start Reading", command=lambda: start_reading(file))
start_button.pack()
stop_button = tk.Button(root, text="Stop Reading", command=stop_reading)
stop_button.pack()
root.mainloop()
In this updated code:
- The stop_flag global variable is used to signal the cancellation of the reading operation.
- The read_tiff function now iteratively reads the file in chunks rather than using a single cv2.imread operation. This allows for periodic checks of the stop_flag in between chunks.
- The stop_reading function simply sets the stop_flag to True, indicating that the reading operation should be cancelled.
With this approach, the reading operation can be paused or cancelled by clicking the "Stop Reading" button. The thread periodically checks the stop_flag to determine if it should stop reading the file.
Note: Modify the file reading code inside the while loop in read_tiff to fit your specific use case.
Please note that canceling a file reading operation may lead to incomplete data processing, so make sure to handle any cleanup or necessary actions appropriately.