How can I redirect stdout into a file in tcl

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).

Leave a Comment