2

I have a For[...] cycle which calls a function. When the function is at work, it prints some text-string through the command Print[...].

Since I iterate the action of the function for 1000 times, the output printed starts to become very long and Mathematica starts to get slow.

Is there any way to modify the Print command or to send the output buffer into a text file which is instantaneously updated?

apt45
  • 1,648
  • 9
  • 14
  • Inside the For loop you could print only each n-th value. If i is your loop variable then try: If[Mod[i, n] == 0, Print[...]; – mrz Jan 17 '18 at 14:12
  • I cannot do that. I am interested in every single output. But it is too long and I want to send it to a text file – apt45 Jan 17 '18 at 14:26

2 Answers2

3

You can use Block to modify the behaviour of Print.

f[x_] := Print[x]

printlist = {};

Block[{Print = AppendTo[printlist, {##}] &},
 Table[f[x], {x, 1, 10}];
 ]

First /@ printlist

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Alternatively you can redirect the output stream.

f[x_] := Print[x]

tmp = $Output;
streamlist = $Output = {OpenWrite[]};

Table[f[x], {x, 1, 10}];

Close@Last@streamlist;
$Output = tmp;
printoutput = ReadList@First@Last@streamlist

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Chris Degnen
  • 30,927
  • 2
  • 54
  • 108
2

You could do something like:

SetAttributes[printToFile, HoldFirst]
printToFile[expr_, file_] := Block[{$Output=OpenAppend[file]},
    Internal`WithLocalSettings[
        Null,
        expr,
        Close[$Output]
    ]
]

Example usage:

printToFile[
    Print[f[x]];Print["asdf"];Print[x/3],
    file
]
Carl Woll
  • 130,679
  • 6
  • 243
  • 355