如何设置全局中止处理程序? [英] How do you set a global Abort handler?

查看:27
本文介绍了如何设置全局中止处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在回答这个问题时,我建议 OP 在他的笔记本开头打开一个流并在最后关闭它.但是,如果生成了 Abort,则流将保持打开状态,如果他们在未先检查的情况下尝试再次打开它,则会造成严重破坏.如果流只需要单个函数,解决方案 会很简单,但整个笔记本都需要它.显然,可以添加一个检查来查看流是否已经打开,但是有没有办法绑定到全局 Abort 处理程序中,以便可以全局处理此类问题?

In answering this question, I suggested that the OP open a stream at the beginning of his notebook and close it at the end. However, if an Abort is generated, the stream will be left open, and will cause havoc if they attempt to open it again without checking first. If the stream was only required for a single function, the solution would be straightforward, but it's required for the entire notebook. Obviously, a check can be added to see if the stream is already open, but is there a way to tie into the global Abort handler so that this type of problem can be handled globally?

编辑:具体来说,我正在寻找一种在发生 Abort 时运行任意代码的方法,无论代码当前是否在CheckAbort.本质上,如果可能的话,我想设置一个全局 Abort 处理程序.如果这存在于笔记本级别,那就更好了.

Edit: to be specific, I'm looking for a way to run arbitrary code when an Abort occurs whether, or not, the code is currently running inside of CheckAbort. Essentially, I'd like to set a global Abort handler, if possible. If this exists at the notebook level, then even better.

推荐答案

作为替代方案,如果您想将效果本地化到单个笔记本,您可以按照以下方式进行操作:

As an alternative, and if you want to localize the effect to a single notebook, you can do something along these lines:

SetOptions[EvaluationNotebook[], 
   CellEvaluationFunction -> 
     (ToExpression[#, StandardForm,
         Function[
            Null,
            Module[{aborted = $Aborted},
              Internal`WithLocalSettings[
                 Null,
                 aborted = (ReleaseHold[Most[Hold[##]]];Last[Hold[##]]),
                 AbortProtect[
                   If[aborted === $Aborted,
                      Print["Did cleanup"]; Abort[]
                   ]]]], 
            HoldAll]] &)
]

注意:重写以纳入@Alexey 的建议

注意 2 已修改以在单个单元格中容纳多个输入.在这种情况下,除最后一个之外的所有输出都被抑制

用您拥有的任何清理代码替换 Print["Did cleanup"] 代码的位置.

where you replace the Print["Did cleanup"] code with whatever cleanup code you have.

这篇关于如何设置全局中止处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆