大家好,
我正在使用 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:
以下是我的部分代码(线程相关代码已经完成,剩下的主要操作我摘录了)。当我使用 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)
最佳答案
问题是由于使用threading.Thread.setDaemon
引起的。设置守护进程的线程不会阻止 Python 解释器退出,但它们仍然继续运行。因为 Python 会在进程终止之前清理环境,所以当线程下面的东西被移除时,线程可能会遇到麻烦。这引发了一个异常,为了您的方便,线程类尝试打印该异常——但随后也失败了,因为该进程正在退出。
您可以尝试使异常静音,但这很棘手(如果线程做了任何实质性的事情,它可能会隐藏一个真正的问题。不过这里不是这种情况。)或者您可以要求线程停止之前 正在退出,并且没有设置线程守护进程。或者您可以完全避免使用线程。我不记得 wxPython 是否有一个方便的机制来获取进程的输出甚至进行异步 I/O,但许多 GUI 工具包都有。而且总是有 Twisted,它会为您完成这一切。
关于退出整个程序时出现python线程异常错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4079810/