I tried to save the Print[] output to a file using this code:

$Output = {};
strm = OpenWrite[FileNameJoin[{DataDir, "output.log"}]];
AppendTo[$Output, strm];

However when I use this method, it does not print the standard output in the notebook. I would like to have both options: output printed in the notebook and also written to a file.

Do you have solution please?

Thank you

  • $\begingroup$ Why you make standard $Output = {}; empty? Just remove that first line and you will see that output will be printed in the notebook as well as sent to the file "output.log". I would also suggest to use "DataDir" (string instead of symbol). $\endgroup$ – Acus Oct 13 '20 at 6:03
  • $\begingroup$ If I don't make it empty, then it saves in the log file all the output, including from previous runnings of the same kernel. for example if I write: strm = OpenWrite[FileNameJoin[{"output.log"}]]; AppendTo[$Output, strm]; Print["test"]; Close[strm]; and run it 3 times separately, the output log will be: test test test $\endgroup$ – GM_jnj Oct 14 '20 at 7:53
  • $\begingroup$ I would be surprised if it were otherwise. Since your run 3 times, your get 3 outputs. Remember that the front end replaces the output each time your run the same cell (unless your change that behaviour in OptionInspector). You can achieve the same effect by deleting the output file itself (when exists) in the first line of code. $\endgroup$ – Acus Oct 14 '20 at 16:50
  • $\begingroup$ Thanks @user18792 - but I still got three times "test" in the output file, even if I deleted it. How can I save only the last output in each run? or any other commands that will do it and in addition will show the output in the notebook? $\endgroup$ – GM_jnj Oct 16 '20 at 14:58

A bit too long for comment. The multiple output was due to multiple append of stream after each evaluation. I added the line If[Length[\$Output] === 1, AppendTo[$Output, strm]]; which checks if the stream was already added to the \$Output. Now it should work as expected. Copy the content into notebook and SAVE it to disk (otherwise the code will not work, because of NotebookDirectory[EvaluationNotebook[]])

 If[! FileExistsQ[
        outputDir = 
      If[FileExistsQ[FileNameJoin[{outputDir, "output.log"}]],
        DeleteFile[FileNameJoin[{outputDir, "output.log"}]]
    strm = OpenWrite[FileNameJoin[{outputDir, "output.log"}]];
    If[Length[$Output] === 1, AppendTo[$Output, strm]];
    Print["test1"]; Print["test2"]; Close[strm];

You can read content of the file directly from Mma.

FilePrint[FileNameJoin[{outputDir, "output.log"}]]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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