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.
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.
- $\begingroup$ I think I first saw this style used by Brett Champion. $\endgroup$Szabolcs– Szabolcs2015-07-31 13:32:39 +00:00Commented Jul 31, 2015 at 13:32
- 2$\begingroup$ This is extremely useful, especially the
HoldAllidea! $\endgroup$Joseph O'Rourke– Joseph O'Rourke2015-07-31 13:55:57 +00:00Commented Jul 31, 2015 at 13:55 - $\begingroup$ @JosephO'Rourke It seems to be used by quite a few internal functions. Try this:
Block[{System`GeoGraphicsDump`geoDebugPrint = Print}, GeoGraphics[]]. $\endgroup$Szabolcs– Szabolcs2015-08-07 11:39:21 +00:00Commented Aug 7, 2015 at 11:39
Seems like you are looking for Inactivate:
ClearAll[x, y]; Inactivate[ Print[x = 1]; Print[y = x + 3]; y, Print] 4
- 3$\begingroup$ Ah, so that is the modern approach… :) $\endgroup$J. M.'s missing motivation– J. M.'s missing motivation2015-07-31 13:21:30 +00:00Commented Jul 31, 2015 at 13:21
- 3$\begingroup$ Block[{modern = lazy}, yes this is the modern approach]. Block is much more powerful of course... esp. with @Szabolcs HoldAll observation $\endgroup$mfvonh– mfvonh2015-07-31 13:48:21 +00:00Commented Jul 31, 2015 at 13:48
- 1$\begingroup$ I don't think this works if the
Prints are in an external script, as inInactivate[<<"foo.m",Print]. $\endgroup$Reb.Cabin– Reb.Cabin2018-10-21 19:18:03 +00:00Commented Oct 21, 2018 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.
Block[{Print = If[$verbose, Print, Identity]}, (* stuff *)]. $\endgroup$Block[{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. $\endgroup$