2

How can I interrupt a read file operation? For example I'm trying to read a big tiff file on network drive and it can sometime take a long time. I want to be able to cancel the reading operation on a button click for example. I read about threading but I can't use an event here since it's not a loop, but a single read operation, and I can't periodically check for a stop event..

def start_reading(path):
    thread = threading.Thread(target=read_tiff(path))
    thread.start()

def read_tiff(path):
        start = time.time()
        print('Start reading\n')
        im = cv2.imread(file)
        print('Read finished: %.3f' % (time.time() - start))

def stop_reading():
....


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()

2 Answers 2

2

You can still use a threading.Event object to signal to the worker thread (read_tiff) if it should early exit in case of a user pressing the stop button. Since cv2.imread is blocking, I suggest streaming the network file into a tempory bytebuffer in increments of small chunks. That way the worker can continue checking the stop event, and early exit if requested by the user. In case the image downloads before the user presses the stop button, you can use numpy and cv2 APIs to decode the byte buffer back to a cv2 image object.

import cv2
import threading
import time
import numpy as np
import tkinter as tk


def start_reading(path, stop):
    stop.clear()
    thread = threading.Thread(target=read_tiff, args=(path, stop))
    thread.start()


def read_tiff(path, stop):
        print("read thread started")
        start = time.monotonic()
        buf = bytearray()
        with open(path, 'br') as f:
            print('Start reading\n')
            chunk = f.read(1024)
            while chunk and not stop.is_set():
                buf.extend(chunk)
                chunk = f.read(1024)
        if stop.is_set():
             print("Thread timed out")
             return
        arr = np.frombuffer(buf, np.uint8)
        img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
        # write to output file to verify it works
        cv2.imwrite('output.tiff', img)
        print('Read finished: %.3f' % (time.monotonic() - start))

file = 'random.tiff'
root = tk.Tk()
stop_event = threading.Event()

start_button = tk.Button(
    root, 
    text="Start Reading", 
    command=lambda: start_reading(file, stop_event),
)
start_button.pack()

stop_button = tk.Button(
    root, 
    text="Stop Reading", 
    command=lambda: stop_event.set()
)
stop_button.pack()

root.mainloop()
3
  • 1
    Minor note: The walrus operator was invented specifically to avoid the repeated/awkward code in your chunking loop. Change the loop to while not stop.is_set() and chunk := f.read(1024): and you can delete both of the chunk = f.read(1024) lines at either end of the loop. Commented Sep 20, 2023 at 21:51
  • 1
    @ShadowRanger Great point! I initially wrote those lines using the assignment expression operator (walrus operator), but I intentionally changed it because I was unsure of the version of Python that OP is using. The operator was introduced in Python 3.8.
    – sjking
    Commented Sep 20, 2023 at 21:57
  • 1
    Thanks a lot!!! This solved it:) I would upvote but I don't have enough rep :/
    – vaindru
    Commented Sep 21, 2023 at 14:21
-1

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:

  1. The stop_flag global variable is used to signal the cancellation of the reading operation.
  2. 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.
  3. 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.

1
  • many global calls to the same variable indicate a good case for using a class for proper encapsulation...
    – darren
    Commented Sep 20, 2023 at 20:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.