How do you set a global Abort handler?

送分小仙女□ 提交于 2019-12-05 11:06:13

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]] &)
]

NOTE: rewritten to incorporate the suggestion of @Alexey

NOTE 2 Modified to accommodate several inputs in a single cell. In that case, all outputs but the last are suppressed

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

A very simple way would be to issue the following at the start of the file:

Close /@ Streams[] // Quiet

The standard streams stdout and stderr cannot be closed and you silence the warning with Quiet. However, this also assumes that you don't have any open streams that you care about.

To handle an Abort and close the stream, you can modify $Post like:

$Post := If[# === $Aborted, Close[strm], #] &

where strm is the stream that you opened.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!