Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I redirect stdout into a file in tcl

Tags:

file

io

tcl

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"
like image 344
Yike.Wang Avatar asked Dec 16 '11 07:12

Yike.Wang


People also ask

How do I use stdout to file?

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.

How do I write to a file in Tcl?

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.

What is stdout in Tcl?

The standard output, stdout , is used by scripts to write data. The standard error, stderr , is used by scripts to write error messages.


1 Answers

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

like image 116
Donal Fellows Avatar answered Oct 23 '22 19:10

Donal Fellows