13

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.

Joseph O'Rourke
  • 4,731
  • 25
  • 42

3 Answers3

18

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.

Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
11

Seems like you are looking for Inactivate:

ClearAll[x, y];
Inactivate[
 Print[x = 1];
 Print[y = x + 3];
 y,
 Print]

4

mfvonh
  • 8,460
  • 27
  • 42
6

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.

george2079
  • 38,913
  • 1
  • 43
  • 110