在Python中停止单个I/O读取文件线程

问题描述 投票:0回答:1

如何中断读取文件操作? 例如,我正在尝试读取网络驱动器上的大 tiff 文件,有时可能需要很长时间。 例如,我希望能够取消单击按钮的读取操作。我读过有关线程的内容,但我不能在这里使用事件,因为它不是循环,而是单个读取操作,而且我无法定期检查停止事件..

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()
python python-multithreading interrupt
1个回答
0
投票

要中断文件读取操作,您可以使用线程和停止标志来发出取消信号。这是集成此功能的代码的更新版本:

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

在此更新的代码中:

  1. stop_flag 全局变量用于表示读取操作的取消。
  2. read_tiff 函数现在以块的形式迭代读取文件,而不是使用单个 cv2.imread 操作。这允许定期检查块之间的 stop_flag。
  3. stop_reading函数只是将stop_flag设置为True,表示应该取消读取操作。

通过这种方式,可以通过点击“停止读取”按钮来暂停或取消读取操作。线程定期检查 stop_flag 以确定是否应该停止读取文件。

注意:修改 read_tiff 中 while 循环内的文件读取代码以适合您的特定用例。

请注意,取消文件读取操作可能会导致数据处理不完整,因此请确保适当地处理任何清理或必要的操作。

© www.soinside.com 2019 - 2024. All rights reserved.