3

How to redirect Mathematica printing and error printing to files?

Sometimes, a Mathematica program

  • 1) uses Print[] to print messages,
  • 2) sometimes, there is side-effect type of printing by some functions without any explicit Print[]
  • 3) and sometimes there is error printing.

How to redirect the above three varieties of printing to (separate) text files, so they can be archived (separately) when the Mathematica kernel is closed?

rcollyer
  • 10,475
  • 4
  • 48
  • 75
qazwsx
  • 25,536
  • 30
  • 72
  • 106

1 Answers1

6

Print[] by default outputs to the stream $Output. Messages go to the $Messages stream. You can redefine these two global variables to redirect the output to a file:

stream = OpenWrite["out.txt", FormatType -> OutputForm]
$Output = {stream}
Mr.Wizard
  • 24,179
  • 5
  • 44
  • 125
Szabolcs
  • 24,728
  • 9
  • 85
  • 174
  • -1 for making me [look like an ass](http://mathematica.stackexchange.com/q/1118/121). ;-p – Mr.Wizard Feb 01 '12 at 18:11
  • @Mr.Wizard You see now why I avoid asking questions (you asked me about it once) :)? I upvoted this one, b.t.w. – Leonid Shifrin Feb 01 '12 at 18:32
  • To save a bit of face, I must state that I *did* test the code I included and it worked correctly for the simple scenario I used. – Szabolcs Feb 01 '12 at 18:33
  • @Leonid lol -- honestly I wish you would reconsider; you are well respected and I doubt a foolish question would change that. Furthermore I am sure you could ask some really interesting, insightful questions if you chose. – Mr.Wizard Feb 01 '12 at 18:36
  • @Szabolcs what's really annoying is that I did not try to solve the problem on my own first, but thought: "oh, here's a good post for mma.SE!" -- I've started a question in Meta relating to this. – Mr.Wizard Feb 01 '12 at 18:37
  • @Mr.Wizard Well, seriously, I was burnt enough with this when doing Physics. I did Astrophysics as undergrad, then switched to Quantum Optics, then Quantum Field Theory and finally Mathematical Physics - and everywhere I did not dig deep enough (I mean, for my taste. I co-authored papers etc, but too many gaps where I relied on some knowledge without carefully testing it. I could easily stay in Physics, get another postdoc etc). With M (which was a hobby), I started from scratch, and did it right. I wish I had this attitude when starting with Physics. Perhaps, I am overdoing it, but so be it. – Leonid Shifrin Feb 01 '12 at 18:44
  • @Leonid whatever you're doing appears to be working quite well. Keep at it. – Mr.Wizard Feb 01 '12 at 19:00
  • @Mr.Wizard Thanks, Paul. Will do my best :) – Leonid Shifrin Feb 01 '12 at 19:08