开发者

TCL: While no key is pressed loop

I would like to run a while loop until the stdin is filled with a character.

puts "Press x + <enter> to stop."
while {开发者_开发知识库[gets stdin] != "x"} {
   puts "lalal"
}

The problem with the code above that it will wait for stdin and I don't want it to wait. I want the code to be executed all the time.

Edit 8th September 2011 - 8.55am

The code is used inside a FPGA tool called System Console (Altera). This does work with TCL Commands, but unfortunately I don't know which it can handle and which it doesn't.


You should use a fileevent on stdin to set a function to be called once the channel becomes readable then use vwait to run the event loop. Your other tasks can be launched using after chains to have work done in pieces without halting the event processing for too long.

proc do_work {args} {...}
proc onRead {chan} {
    set data [read $chan]
    if {[eof $chan]} {
        fileevent $chan readable {}
        set ::forever eof
    }
    ... do something with the data ...
}
after idle [list do_work $arg1]
fconfigure stdin -blocking 0 -buffering line
fileevent stdin readable [list onRead stdin]
vwait forever


If you put the stdin channel into non-block mode, the gets stdin will return the empty string (and fblocked stdin will then be able to return 1) when input is not available, instead of waiting for something to happen.

# Enable magic mode!
fconfigure stdin -blocking 0

puts "Press x + <enter> to stop."
while {[gets stdin] != "x"} {
   puts "lalal"
   after 20;           # Slow the loop down!
}

# Set it back to normal
fconfigure stdin -blocking 1

In fact, you can also use the system stty program to do even more fancy things.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜