停止迭代异常

StopIteration exception

函数

def _copying(self):
    result = self.result.toPlainText().strip().split('\n')
    to_copy = '\n'.join(result)

    pyperclip.copy(to_copy)

在我的 PyQt5 项目的 MainWindow() 中引发异常 "StopIteration" 在 contextlib.py _GeneratorContextManager(), line 119 'next(self.gen)' 中。 result 是一个 ui.TextEdit 对象。你能告诉我这是什么意思吗? Google 说我应该将我的 func 包装到 with-construction 中,但我真的不明白如何做,也不确定这是个好主意。

调试器说:

__exception__ = {tuple} <class 'tuple'>: (<class 'StopIteration'>, StopIteration(), <traceback object at 0x045DA918>)
 0 = {type} <class 'StopIteration'>
  args = {getset_descriptor} <attribute 'args' of 'BaseException' objects>
  value = {member_descriptor} <member 'value' of 'StopIteration' objects>
 1 = {StopIteration} 
  args = {tuple} <class 'tuple'>: ()
  value = {NoneType} None
 2 = {traceback} <traceback object at 0x045DA918>
  tb_frame = {frame} __exit__ [contextlib.py:119]  id:54111736
  tb_lasti = {int} 16
  tb_lineno = {int} 119
  tb_next = {NoneType} None
 __len__ = {int} 3

控制台什么也没说。但是项目崩溃了。

StopIteration 完全正常且符合预期。这是 contextlib.contextmanager 正常运行的一部分。它应该发生,并且立即被捕获并处理;如果没有,那就有问题了。

我不知道你是怎么看到这个异常的,考虑到它永远不会逃脱 contextlib 内部结构,但如果你把它归咎于你代码的问题,你怪错了。