9
$\begingroup$

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.

$\endgroup$
1
  • $\begingroup$ I didn't find an easy solution ... but why don't you just use CopyFile[] ? $\endgroup$ Commented Mar 31, 2012 at 20:22

1 Answer 1

5
$\begingroup$

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"
$\endgroup$
2
  • $\begingroup$ You shouldn't use LaTeX to do code formatting; LaTeX is there for formulas. Code formatting is done by simply indenting the code by four spaces. To code-format small snippets embedded in the text (like FilePrint or $Output), enclose the snippet in backquotes. $\endgroup$
    – celtschk
    Commented Oct 15, 2012 at 12:27
  • $\begingroup$ @celtschk Thanks for the formatting tips. I've edited the post using your advice. $\endgroup$
    – m_goldberg
    Commented Oct 15, 2012 at 12:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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