Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

How can I capture output from Print from a function which does not leave the printed object as its final output, (and which I do not wish to edit)? E.g.

Module[{},
 Print[Plot[Sin[x], {x, 0, 2 Pi}]];
 a = 123]

I would like to use something like a temporary setting for $PrePrint or $Post, rather than use cell selection (SelectionMove, NotebookRead).

The aim is somehow to intercept the Print output -- the plot object -- and set it to a variable, (without altering the module).

This attempt did not work:-

enter image description here

share|improve this question
    
I probably don't understand the problem but doesn't Print[Sow@Plot[Sin[x], {x, 0, 2 Pi}]] and // Reap at the end captures Print output? –  BoLe Apr 3 '13 at 11:00
    
Do you want the 123 being stored, the plot, or both? –  belisarius Apr 3 '13 at 11:14
    
I just want to pick up the plot object. The problem is the module should not be edited, otherwise it would be simple to set a variable inside the Print command. –  Chris Degnen Apr 3 '13 at 12:11
    
So you want something like $PrePrint or $Post which would also capture the output of Plot[Sin[x],{x,-5,5}];? –  acl Apr 3 '13 at 12:32
    
@acl - Yes, as I have done below using $Output. But setting a variable with $PrePrint could be neater. –  Chris Degnen Apr 3 '13 at 12:56

2 Answers 2

I have found one solution, using a temporary file:-

streams = AppendTo[$Output, OpenWrite[]];

Module[{},
  Print[Plot[Sin[x], {x, 0, 2 Pi}]];
  a = 123];

Close@Last@streams;
$Output = Most@streams;
printoutput = ReadList@First@Last@streams

enter image description here

share|improve this answer

You can temporarily redefine Print, like so:

fun[] := Module[{}, Print[Plot[Sin[x], {x, 0, 2 Pi}]];
  a = 123]

list = {};
Block[{Print = AppendTo[list, {##}] &}, fun[]]

Now list contains everything that was printed. (Of course in a practical application you'd probably want to do something smarter than an inefficient periodic AppendTo)

If you still want to print the expressions while simultaneously saving them, use the Villegas-Gayley trick to redefine Print.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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