Can I print to a different notebook? (within the context of the same kernel)
As Yves already mentioned, you can easily create and edit notebooks through Mathematica commands. A start would be this tutorial, which you can find in the Documentation Center under tutorial/ManipulatingNotebooksFromTheKernel
Here is a short example printing the i
values into a new notebook:
nb = CreateDocument[];
For[i = 1, i <= 10, i++,
SelectionMove[nb, Next, Cell];
NotebookWrite[nb,
Cell[BoxData@RowBox[{"i is now ", ToString[i]}], "Output"]];
]
If you want to know how to construct cell expressions, you could just go over any cell in a notebook and hit Ctrl+Shift+E to see the underlying structure.
Although the question has been answered, no reason for this question was given. One possible motivation is to be able to discard a lot of diagnostic output, e.g. from an iterative process, by trashing the newly created notebook.
In such a case an alternative could be Dynamic[.], e.g.
ClearAll[iter];
Dynamic[iter]
For[i = 1, i <= 10, i++,
Pause[1.0];
iter = "i is now " <> ToString[i]
]
Here's what I have been using.
Any improvements / comments are welcome.
(* this opens a notebook file and if notebook exists it CLEARS the contents as well *)
OpenNB[fname_] := Module[{dir, fns, nb},
dir = NotebookDirectory[];
fns = FileNames[FileNameJoin[{dir, fname}]];
If[fns === {}, (
nb = CreateNotebook[];
NotebookSave[nb, FileNameJoin[{dir, fname}]];
), (
nb = NotebookOpen[fns[[1]]];
SelectionMove[nb, All, Notebook];
NotebookDelete[nb];
)
];
Return[nb];
];
PrintNB[style_String: "Print", nb_NotebookObject: EvaluationNotebook[], args__] := NotebookWrite[nb, Cell[BoxData@ToBoxes[SequenceForm[args]], style]];
Here is example usage
logNB = OpenNB["log.nb"];
PrintNB[logNB, "Execution Log for: ", NotebookFileName[]];
PrintNB[logNB, "Started at: ", DateString[]];
f[r] = r^\[Gamma]*Exp[-\[Kappa] r];
PrintNB[logNB, "f(r) = ", f[r]];
PrintNB["PageBreak", logNB, " "];
PrintNB[logNB, "Hello"];
Here is the output