I recently wanted to use FilePrint to print the contents somewhere else but in the notebook I was using. However, the obvious-seeming solution doesn't work at all:
In[137]:= temp = With[{str = OpenWrite[]},
Block[{$Output = str},
Print["fee fi fo fum"]];
Close[str]];
In[138]:= FilePrint[temp]
"fee fi fo fum"
In[139]:= With[{str=OpenWrite[]},
Block[{$Output = str},
FilePrint[temp]];
Close[str]];
"fee fi fo fum"
Since the obvious solution doesn't work, does anybody know a less obvious solution, preferably one that doesn't involve re-implementing FilePrint myself? Sure, that would be easy, but I'd prefer not to do it.
Answer
I can only give a partial answer. Your problem arises because FilePrint doesn't use $Output (stdout). It uses the stderr stream, so you can't capture what it writes by using Block and assigning to $Output. Unfortunately, I don't think any system variable is bound to stderr. Perhaps I'm wrong. In that case, I hope a more knowable person will be able to complete this answer.
In case anyone is interested, here is how I discovered that FilePrint was using stderr.
text = "fee fi fo fum";
output = With[{str = OpenWrite[]},
Block[{$Output = str},
Print[text]];
Close[str]];
FilePrint[Print[Streams[]]; output]
{OutputStream[stdout,1],OutputStream[stderr,2]}
"fee fi fo fum"
Comments
Post a Comment