4

How can I make g[]; or h[]; print the same output as f[];? I am trying to capture the output of one function and put it in a document elsewhere, but the CellPrint output is not cooperating.

f[] := Module[{},
  Print["Bob"];
  CellPrint[Cell["", Background -> Blue, "Print"]];
  Print["Bill"]]

printlist = {};
Block[{Print = AppendTo[printlist, {##}] &,
   CellPrint = AppendTo[printlist, {##}] &}, f[]];

g[] := Map[CellPrint, ExpressionCell[#, "Print"] & /@
    Flatten[printlist, 1]]

h[] := CreateDocument[ExpressionCell[#, "Print"] & /@
    Flatten[printlist, 1]]

f[];
g[];
Kuba
  • 136,707
  • 13
  • 279
  • 740
Chris Degnen
  • 30,927
  • 2
  • 54
  • 108

3 Answers3

2

a) notice that depending on the settings Print may be printed to the MessagesNotebook while CellPrint always goes to the parent notebook.

b) I'm not sure what is the context so I will just leave those links here:

Can I Print to a different notebook? (within the context of the same kernel)

Temporarily redirect the output of Print[ ] to a second file

c) the answer:

The problem is that you are doing CellPrint @ ExpressionCell @ Cell[.... Here is what you can do:

f[] := Module[{}, Print["Bob"];
  CellPrint[Cell["", Background -> Blue, "Print"]];
  Print["Bill"]]

printlist = {};
Block[{Print = 
    AppendTo[printlist, ExpressionCell[Row[{##}], "Print"]] &, 
   CellPrint = AppendTo[printlist, {##}] &}, f[]];

g[] := Map[CellPrint, Flatten[printlist, 1]]

h[] := CreateDocument[Flatten[printlist, 1]]

f[];
g[];
Kuba
  • 136,707
  • 13
  • 279
  • 740
2

Why not wrap ExpressionCell only around Print calls? For example:

printlist={};
Block[
    {
    Print = AppendTo[printlist, Thread[ExpressionCell[{##}, "Print"]]]&,
    CellPrint = AppendTo[printlist, #]&
    },
    f[]
];

g[] := CellPrint /@ Flatten @ printlist
h[] := CreateDocument[
    Flatten @ printlist
]

Then:

g[];

enter image description here

and:

nb = h[];
CurrentNotebookImage[nb]

enter image description here

seem to do what you want.

Carl Woll
  • 130,679
  • 6
  • 243
  • 355
2

CellPrint >> Details:

In CellPrint[expr]:

If expr has head TextCell, ExpressionCell, or CellGroup, it is inserted unchanged into the notebook.

So changing heads Cell to Sequence in the first argument of ExpressionCell works:

ClearAll[g, h]

g[] := Map[CellPrint, ExpressionCell[# /. Cell -> Sequence, "Print"] & /@ 
   Flatten[printlist, 1]]

h[] := CreateDocument[ExpressionCell[# /. Cell -> Sequence, "Print"] & /@ 
   Flatten[printlist, 1]]

g[];

enter image description here

h[]

enter image description here

kglr
  • 394,356
  • 18
  • 477
  • 896