【问题标题】:Interrupting Python blocks with exception catchers使用异常捕获器中断 Python 块
【发布时间】:2020-07-31 16:34:47
【问题描述】:

这似乎是一个非常明显但令人讨厌的问题。 考虑这里的代码块 -

for i in tqdm.notebook.tqdm(range(int(3*len(structures)/4))):
    try:
        is_mal=np.array([1.]) if 'Malware' in structure_info[i] else np.array([0.])
        target=parse_Structure(file=structures[i])
        target=np.reshape(target.get_vector(),(-1,1))
        is_mal=np.reshape(is_mal,(-1,1))
        vectors=np.concatenate((vectors,target), axis=1)
        labels=np.concatenate((labels,is_mal), axis=1)
    except:
        print(i)

无论如何,代码都无关紧要。但我有一个简单的问题。

在我的 Colab Notebook 在线环境中运行此程序时,当我想在循环中间调试某些内容时,我只是尝试中断执行。

这导致打印循环所在的索引,显然中断被视为异常。虽然我同意循环完美执行 try-catch 块这一事实,但我也想严重中断执行。

如何在不重新启动运行时中断此块的执行?

【问题讨论】:

    标签: python python-3.x try-catch execution interruption


    【解决方案1】:

    您可以在 except 块内引发新异常以将其继续传递:

    try:
      <code>
    except:
      raise Exception
    

    如果您想重新引发已捕获的相同异常:

    try:
      <code>
    except Exception as E:
      raise E
    

    这会将异常传递给下一个处理程序,如果没有其他尝试/例外,它将停止整个脚本。

    如果您被Exception 未捕获的内容(例如Ctrl-C)打断,您可以将Exception 替换为BaseExceptionKeyboardInterrupt。请注意,后面这两个应该很少被完全捕获并且不会在生产环境中重新提出,因为这可能会使再次实际退出程序变得很麻烦。

    有关异常的更多信息:https://docs.python.org/3/library/exceptions.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-04
      • 2010-09-28
      • 1970-01-01
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 2017-12-30
      相关资源
      最近更新 更多