3

我正在运行一个 Tkinter GUI,它subprocess.Popen(...)使用 stdout 和 stderr 分离另一个进程(python 脚本)并使用管道。然后我将分离一个单独的线程以异步读取该进程中的 out/err 并将其绘制到 Tkinter Text 小部件中threading.Thread

一切都很好,除了异步。读取线程仅在我移动鼠标或按下键盘上的键时执行。我什至将打印语句放入线程函数中,当我在圆圈中移动鼠标时它们开始/停止打印。

这是我正在使用的异步读取类,从这里借来的:

class AsynchronousFileReader(threading.Thread):
    '''
    Helper class to implement asynchronous reading of a file
    in a separate thread. Pushes read lines on a queue to
    be consumed in another thread.
    '''

    def __init__(self, fd, queue):
        assert isinstance(queue, Queue.Queue)
        assert callable(fd.readline)
        threading.Thread.__init__(self)
        self._fd = fd
        self._queue = queue

    def run(self):
        '''The body of the tread: read lines and put them on the queue.'''
        for line in iter(self._fd.readline, ''):
            self._queue.put(line)

    def eof(self):
        '''Check whether there is no more content to expect.'''
        return not self.is_alive() and self._queue.empty()

还有我的从异步文件阅读器中提取消息的消耗方法(这是在单独的线程上运行的方法:

def consume(self, process, console_frame):
    # Launch the asynchronous readers of the process' stdout and stderr.

    stdout_queue = Queue.Queue()
    stdout_reader = AsynchronousFileReader(process.stdout, stdout_queue)
    stdout_reader.start()
    stderr_queue = Queue.Queue()
    stderr_reader = AsynchronousFileReader(process.stderr, stderr_queue)
    stderr_reader.start()

    # Check the queues if we received some output (until there is nothing more to get).
    while not stdout_reader.eof() or not stderr_reader.eof():
        # Show what we received from standard output.
        while not stdout_queue.empty():
            line = stdout_queue.get()
            console_frame.writeToLog(line.strip(), max_lines=None)
            time.sleep(.03) # prevents it from printing out in large blocks at a time

        # Show what we received from standard error.
        while not stderr_queue.empty():
            line = stderr_queue.get()
            console_frame.writeToLog(line.strip(), max_lines=None)
            time.sleep(.03) # prevents it from printing out in large blocks at a time

        # Sleep a bit before asking the readers again.
        time.sleep(.05)

    # Let's be tidy and join the threads we've started.
    stdout_reader.join()
    stderr_reader.join()

    # Close subprocess' file descriptors.
    process.stdout.close()
    process.stderr.close()

    print "finished executing"
    if self.stop_callback:
        self.stop_callback()

就像我之前说的——consume()线程只在我移动鼠标或在键盘上键入时执行——这意味着writeToLog(...)函数(用于将文本附加到 Tkinter GUI 中)只有在鼠标/键盘活动发生时才会执行......有什么想法吗?

编辑:我想我可能对正在发生的事情有所了解......如果我评论writeToLog(...)调用并将其替换为简单的打印(将 Tkinter 排除在等式之外),那么消耗线程将正常执行。看来 Tkinter 是这里的问题。关于我可以从消费线程完成 Tkinter 文本小部件更新的任何想法?

EDIT2:感谢评论,让它工作。这是我使用的最终代码:

gui_text_queue = Queue.Queue()


def consume(self, process, console_frame):
    # Launch the asynchronous readers of the process' stdout and stderr.

    stdout_queue = Queue.Queue()
    stdout_reader = AsynchronousFileReader(process.stdout, stdout_queue)
    stdout_reader.start()
    stderr_queue = Queue.Queue()
    stderr_reader = AsynchronousFileReader(process.stderr, stderr_queue)
    stderr_reader.start()

    # Check the queues if we received some output (until there is nothing more to get).
    while not stdout_reader.eof() or not stderr_reader.eof():
        # Show what we received from standard output.
        while not stdout_queue.empty():
            line = stdout_queue.get()
            gui_text_queue.put(line.strip())

        # Show what we received from standard error.
        while not stderr_queue.empty():
            line = stderr_queue.get()
            gui_text_queue.put(line.strip())

        # Sleep a bit before asking the readers again.
        time.sleep(.01)

    # Let's be tidy and join the threads we've started.
    stdout_reader.join()
    stderr_reader.join()

    # Close subprocess' file descriptors.
    process.stdout.close()
    process.stderr.close()

    if self.stop_callback:
        self.stop_callback()

将此方法添加到我的 Tkinter 控制台框架中,并在框架初始化程序结束时调用它一次:

def pull_text_and_update_gui(self):
    while not gui_text_queue.empty():
        text = gui_text_queue.get()
        self.writeToLog(text, max_lines=None)
    self.after(5, self.pull_text_and_update_gui)
4

1 回答 1

3

Tkinter 不是线程安全的。如果您的writeToLog函数尝试将数据插入到文本小部件中,您将得到不可预知的行为。为了让单独的线程将数据发送到小部件,您需要将数据写入线程安全队列,然后让主线程轮询该队列(使用 tkinter 的after方法)。

于 2012-08-05T23:16:23.780 回答