Run TCL script in regular intervals with continuous results

I have encountered a problem in one of my TCL scripts. I need to run it in an infinite loop with a terminating condition and in every loop I need to write some output. This is the basic code that im using:

proc wr {i} {
    puts -nonewline "$i"
}

proc do {roof} {
    set end 0
    while {$end < $roof} {
        after 1000
        wr $end
        incr end
    }
}

do 10

The expected behaviour is that every second there will be a new output until $end == $roof. But instead after running this script, the console window is busy for 10 seconds and after that time, the entire output prints out at once.

Thank you for your advice :)

Upvotes: 2

Views: 1020

Answers (1)

Johannes Kuhn
Johannes Kuhn

Reputation: 15163

The problem is that you don't flush stdout.

If you modify your script so it flushes stdout:

proc wr {i} {
    puts -nonewline "$i"
    flush stdout
}

proc do {roof} {
    set end 0
    while {$end < $roof} {
        after 1000
        wr $end
        incr end
    }
}

do 10

It will work. You can also change the buffering of the stdout channel to none, the default is line:

fconfigure stdout -buffering none

If you write more than one line, the default buffering will flush stdout when it encounters a newline, but you never write a newline.

Upvotes: 4

Related Questions