How do you set a global Abort handler?

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?

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

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.

链接地址: http://www.djcxy.com/p/35610.html

上一篇: Mathematica编程图形图

下一篇: 你如何设置全局中止处理程序?