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"
Redirecting stdout and stderr to a file: The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator.
Set the file pointer to the end of the file prior to each write. a+ Open the file for reading and writing. If the file does not exist, create a new empty file. Set the initial access position to the end of the file.
The standard output, stdout , is used by scripts to write data. The standard error, stderr , is used by scripts to write error messages.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With