0

Question is extension of what is answered in link. While trying to use it to print output with delay, cat file_name on the shell doesn't display the content of the file during the delay time using after. Here's the code:

proc foo {times} { 
    while {$times >0} {
        puts "hello$times"
        incr times -1
        after 20000
        puts "hello world" 
    }
}
proc reopenStdout {file} {
    close stdout
    open $file w        ;# The standard channels are special
}

reopenStdout ./bar
foo 10

1 Answers1

0

The data you're writing is being buffered in memory and you're not writing enough of it to flush the internal buffer to disk. Add a flush stdout inside the loop in foo, or do something like set up the newly opened channel to be line-buffered:

proc reopenStdout {file} {
    close stdout
    set ch [open $file w]        ;# The standard channels are special
    chan configure $ch -buffering line
}

You can play with chan configure's -buffering and -buffersize options to get the behavior that works best for your needs if line buffering isn't enough.

Shawn
  • 47,241
  • 3
  • 26
  • 60
  • Yes i thought so too, but why does the `puts "hello world"` in the original answer there was no need for flush? is that because the program/script reached end and an automatic flush was done? – almostacoder Sep 09 '21 at 09:31
  • 1
    @almostacoder Channels are flushed when they're closed, yeah (explicitly or at exit) – Shawn Sep 09 '21 at 18:54