tcl - 如何编写一个在无限循环中执行某些操作的 TCL 程序,直到检测到用户按键?
问题描述
我不确定在 TCL 中如何做到这一点。所以基本上,我需要编写一个程序,它会以 500 毫秒的间隔执行,直到按下一个键。按键基本上会导致它退出。这怎么能用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
推荐阅读
- shell - Makefile:重用环境变量
- bash - 等待 Live555 进程完成
- r - 如何从 TCGAquery_recount2 的返回对象中提取 colnames
- mongodb - 根据另一个文档值查找匹配条件的文档
- java - 如何在适配器外部的 ListView 和 GridView 中获取项目位置?
- django - Django .query 属性行为
- redisson - 为什么 reddison ExpirationEntry 使用 LinkedHashMap 来保存 Thread?
- angular - 角度路由:无法导航到命名插座的同级路由
- optaplanner - Optaplanner - 为什么从 full_assert 模式切换到另一种模式会产生完全不同的结果?
- postgresql - 我们如何在 postgresql 中构建查询以在从其他列中提取时间数据类型为 null 的列值显示为 0 或 null