我想分享 Todd Gayley(Wolfram Research)针对给定问题提出的一个很好的技巧。也许对某人有用,对我也有用。这个技巧以相当优雅的方式解决了所讨论的问题。
一种技术是离开
OutputForm 的 FormatType 为
计算,但覆盖
暂时处理消息
切换到 StandardForm,以便仅
消息输出返回
标准格式:
LinkWrite[link,
Unevaluated[EnterExpressionPacket[
Unprotect[Message];
Message[args___]:=
Block[{$inMsg = True, result},
SetOptions[$Output, FormatType->StandardForm];
result = Message[args];
SetOptions[$Output, FormatType->OutputForm];
result
] /; !TrueQ[$inMsg]
]
]]
您将得到一个包含 a 内容的 ExpressionPacket
信息。要将其打印为消息单元格中的
笔记本:
cell = Cell[<the ExpressionPacket>, "Message", "MSG"]
CellPrint[cell]
高级方法:所有内容都以 StandardForm 形式打印
为了让除了输出之外的所有内容都返回StandardForm
我们可以重新定义变量$Pre
and $Post
以特殊方式在从属内核中(应在从属内核中评估以下代码):
SetOptions[$Output, {PageWidth -> 72, FormatType -> StandardForm}];
(*$inPost is needed for tracing mode compatibility
(could be switched on by evaluating On[] in the slave kernel)
in which Messages are printed during evaluation of $Post.*)
$inPost = False; Protect[$inPost];
$Pre := Function[inputexpr,
SetOptions[$Output, FormatType -> StandardForm];
Unevaluated[inputexpr], HoldAllComplete];
$Post := Function[outputexpr,
Block[{$inPost = True},
SetOptions[$Output, FormatType -> OutputForm];
Unevaluated[outputexpr]], HoldAllComplete];
Protect[$Pre]; Protect[$Post];
$inMsg = False; Protect[$inMsg];
Unprotect[Message];
Message[args___] /; $inPost := Block[{$inMsg = True},
SetOptions[$Output, FormatType -> StandardForm];
Message[args];
SetOptions[$Output, FormatType -> OutputForm]] /; ! $inMsg;
Protect[Message];