退出整个程序时python线程异常错误

pep*_*ero 1 python multithreading wxpython exception

嗨,大家好,

我正在使用 python 2.4.3 和 wxpython 开发 GUI。一切正常,除非我退出主程序(关闭 GUI 的主窗口)。奇怪的是,有时有这样的错误,有时根本没有错误。虽然我从 python 邮件列表中发现了相同的错误报告(链接是http://bugs.python.org/issue1722344,我不确定我的情况是否与这个相同)。我不知道它最终是如何解决的,我应该怎么做才能克服这个问题。

来自控制台的错误消息如下。

Exception in thread Thread-1 (most likely raised during interpreter shutdown):
Traceback (most recent call last):
  File "/usr/lib/python2.4/threading.py", line 442, in __bootstrap
  File "/opt/company/workspace/username/application/src/mainwidget.py", line 1066, in run
  File "/usr/lib/python2.4/Queue.py", line 89, in put
  File "/usr/lib/python2.4/threading.py", line 237, in notify
exceptions.TypeError: exceptions must be classes, instances, or strings (deprecated), not NoneType
Unhandled exception in thread started by 
Error in sys.excepthook:

Original exception was:
Run Code Online (Sandbox Code Playgroud)

下面是我的部分代码(线程相关的代码已经完成,剩下的我提取主要操作)。当我使用 GUI 启动外部子进程时,同时创建了一个 wx.TextCtrl 对象。这个 wx.TextCtrl 对象用于给出外部子进程的输入和打印输出

class BashProcessThread(threading.Thread):
    def __init__(self, readlineFunc):
        threading.Thread.__init__(self)
        self.readlineFunc = readlineFunc
        self.lines = []
        self.outputQueue = Queue.Queue()
        self.setDaemon(True)

    def run(self):
        while True:
           line = self.readlineFunc()
           self.outputQueue.put(line)
           if (line==""):
            break
        return ''.join(self.lines)

    def getOutput(self):
        """ called from other thread """            
        while True:
            try:
                line = self.outputQueue.get_nowait()
                lines.append(line)
            except Queue.Empty:
                break
        return ''.join(self.lines)

class ExternalProcWindow(wx.Window):
    def __init__(self, parent, externapp):
        wx.Window.__init__(self, parent, -1, pos=wx.DefaultPosition, size = wx.Size(1200, 120))
        self.externapp=externapp
        self.prompt = externapp.name.lower() + '>>'
        self.textctrl = wx.TextCtrl(self, -1, '', size= wx.Size(1200, 120), style=wx.TE_PROCESS_ENTER|wx.TE_MULTILINE)
        self.default_txt = self.textctrl.GetDefaultStyle()
        self.textctrl.AppendText(self.prompt)
        self.outputThread = BashProcessThread(self.externapp.sub_process.stdout.readline)
        self.outputThread.start()
        self.textctrl.SetFocus()
        self.__bind_events()         
        self.Fit()

    def __bind_events(self):
        self.Bind(wx.EVT_TEXT_ENTER, self.__enter)

    def __enter(self, e):
        nl=self.textctrl.GetNumberOfLines()
        ln =  self.textctrl.GetLineText(nl-1)
        ln = ln[len(self.prompt):]     
        self.externapp.sub_process.stdin.write(ln+"\n")
        time.sleep(.3)
        self.textctrl.AppendText(self.outputThread.getOutput())

class ExternApp:
    def launch(self):
        self.sub_process = subprocess.Popen(launchcmd, stdin=subprocess.PIPE, 
                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Run Code Online (Sandbox Code Playgroud)

Tho*_*ers 5

问题是由于使用threading.Thread.setDaemon. 设置守护进程的线程不会阻止 Python 解释器退出,但它们仍会继续运行。因为 Python 在进程终止之前清理了环境,所以当从它们下面移除东西时,线程可能会遇到麻烦。这引发了一个异常,线程类为了您的方便而尝试打印该异常——但是,由于进程正在退出,它也失败了。

您可以尝试使异常静音,但这很棘手(如果线程做了任何实质性的事情,它可能会隐藏一个真正的问题。不过这里不是这种情况。)或者您可以要求线程退出之前停止,而不是设置线程守护进程。或者您可以完全避免使用线程。我不记得 wxPython 是否有一种方便的机制来获取进程的输出甚至进行异步 I/O,但许多 GUI 工具包都有。并且总是有 Twisted,它为您完成这一切。