首页 > 解决方案 > 如何编写一个在无限循环中执行某些操作的 TCL 程序,直到检测到用户按键?

问题描述

我不确定在 TCL 中如何做到这一点。所以基本上,我需要编写一个程序,它会以 500 毫秒的间隔执行,直到按下一个键。按键基本上会导致它退出。这怎么能用TCL写?我不知道如何检测 TCL 中的按键。

标签: tcl

解决方案


tcl 事件循环使它变得容易。棘手的一点是将您的终端设置为原始模式,以便按键不会被缓冲。Tcler的 Wiki 展示了如何用于 Unix 和 Windows 系统。

Unix 示例:

#!/usr/bin/env tclsh

proc enableRaw {{channel stdin}} {
   exec /bin/stty raw -echo <@$channel
}
proc disableRaw {{channel stdin}} {
   exec /bin/stty -raw echo <@$channel
}

proc timer {} {
    puts "Waiting for keypress..."
    after 500 timer ;# Re-schedule the looping procedure
}

proc read_key {} {
    set c [read stdin 1]
    if {[string length $c] == 1 || [chan eof stdin]} {
        global done
        puts "Got a keypress!"
        set done 1 ;# Exit the event loop.
    }
}

# Set up stdin to be non-blocking and register a callback function
# for when it's readable, and set it to raw mode
chan configure stdin -blocking 0 -buffering none
chan event stdin readable read_key
enableRaw
# Start the timer
after 500 timer
# And enter the event loop
vwait done
# Restore the terminal to normal cooked mode
disableRaw

推荐阅读