4
$\begingroup$

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[];
$\endgroup$
2
$\begingroup$

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

$\endgroup$
2
$\begingroup$

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[];
$\endgroup$
2
$\begingroup$

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.

$\endgroup$

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.