2
$\begingroup$

This question already has an answer here:

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?

$\endgroup$

marked as duplicate by Jason B., Community Jan 17 '18 at 16:59

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\begingroup$ 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[...]; $\endgroup$ – mrz Jan 17 '18 at 14:12
  • $\begingroup$ 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 $\endgroup$ – apt45 Jan 17 '18 at 14:26
3
$\begingroup$

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}

$\endgroup$
2
$\begingroup$

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
]
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.