log_thread.py 1.22 KB
# -*- coding: utf-8 -*-
import wx
from Queue import Queue
from threading import Thread
import copy

class RThread(Thread):

    def __init__(self, target, args, kwargs):
        self.target = target
        self.args = args
        self.kwargs = kwargs
        self.result = None
        Thread.__init__(self)

    def run(self):
        self.result = self.target(*self.args, **self.kwargs)

class LogThread(Thread):

    def __init__(self, text_ctrl, target, on_end=None, args=(), kwargs={}):
        self.text_ctrl =  text_ctrl
        self.target = target
        self.on_end = on_end
        self.args = args
        self.kwargs = kwargs
        Thread.__init__(self)

    def run(self):
        queue = Queue()
        kwargs = copy.copy(self.kwargs)
        kwargs["log"] = queue
        worker = RThread( target=self.target
                       , args=self.args
                       , kwargs=kwargs )
        worker.start()
        while True:
            msg = queue.get()
            if msg is None:
                break
            wx.CallAfter(self.print_msg, msg)
        worker.join()

        if self.on_end:
            wx.CallAfter(self.on_end, worker.result)

    def print_msg(self, msg):
        self.text_ctrl.AppendText(msg)