How can I redirect stdout into a file in tcl

tcl
Yike.Wang picture Yike.Wang · Dec 16, 2011 · Viewed 38.2k times · Source

how can I redirect a proc output into a file in tcl, for example, I have a proc foo, and would like to redirect the foo output into a file bar. But got this result

% proc foo {} { puts "hello world" }
% foo
hello world
% foo > bar
wrong # args: should be "foo"

Answer

Donal Fellows picture Donal Fellows · Dec 16, 2011

If you cannot change your code to take the name of a channel to write to (the most robust solution), you can use a trick to redirect stdout to a file: reopening.

proc foo {} { puts "hello world" }
proc reopenStdout {file} {
    close stdout
    open $file w        ;# The standard channels are special
}

reopenStdout ./bar
foo
reopenStdout /dev/tty   ;# Default destination on Unix; Win equiv is CON:

Be aware that if you do this, you lose track of where your initial stdout was directed to (unless you use TclX's dup to save a copy).