I have a complex program that prints out lots of diagnostic/tracing information. Is there some mechanism to evaluate it and suppress all printing? I know I could protect every Print[ ] with If[printswitch, Print[...]]. But it would be convenient if there were some way to shunt all printing to /dev/null rather than to the notebook, or its functional equivalent.
- 4,731
- 25
- 42
3 Answers
One common way to deal with diagnostic messages is something like this:
Instead of Print use some other head of your choosing, e.g. debugPrint.
f[x_] := (debugPrint["x is ", x]; x^2)
Now you can either simply define debugPrint = Print to enable messages permanently, or you can do it temporarily in a localized way with
Block[{debugPrint = Print}, f[5]]
This is both simpler to write and more flexible to manage than flags and If constructs (as in If[flag, Print[...]]).
An improvement to the technique is to set
SetAttributes[debugPrint, HoldAll]
Now when we write debugPrint[f[x]], the argument f[x] won't even be computed unless debugPrint = Print is set. This way debugPrint[ expensiveToComputeFunction[x] ] won't slow down your functions when debugging is turned off.
- 234,956
- 30
- 623
- 1,263
-
-
2
-
@JosephO'Rourke It seems to be used by quite a few internal functions. Try this:
Block[{System`GeoGraphicsDump`geoDebugPrint = Print}, GeoGraphics[]]. – Szabolcs Aug 07 '15 at 11:39
Seems like you are looking for Inactivate:
ClearAll[x, y];
Inactivate[
Print[x = 1];
Print[y = x + 3];
y,
Print]
4
- 8,460
- 27
- 42
-
3
-
3Block[{modern = lazy}, yes this is the modern approach]. Block is much more powerful of course... esp. with @Szabolcs HoldAll observation – mfvonh Jul 31 '15 at 13:48
-
I don't think this works if the
Prints are in an external script, as inInactivate[<<"foo.m",Print]. – Reb.Cabin Oct 21 '18 at 19:18
This works for simple things
output = $Output;
$Output = OpenWrite["/dev/null"]; (*or "NUL" on windows *)
Print["suppressed"];
Close[$Output];
$Output = output;
Not sure if it might have some unintended side effects.
- 38,913
- 1
- 43
- 110
Block[{Print = If[$verbose, Print, Identity]}, (* stuff *)]. – J. M.'s missing motivation Jul 31 '15 at 12:48Block[{sym}, expr]evaluatesexprwith the definition ofsymtemporarily removed. This works even ifsymis a builtin likePrint.Block[{Print}, ...]makesPrintbehave like any undefined symbol while the body of theBlockis evaluated. – Szabolcs Jul 31 '15 at 13:42