下面是一段代码,它通过命令提示符 MyShell >
实现了一个交互式 TCL session 。
puts -nonewline stdout "MyShell > "
flush stdout
catch { eval [gets stdin] } got
if { $got ne "" } {
puts stderr $got
}
此代码在终端提示 MyShell >
并等待输入按钮被点击;虽然它没有被击中,但代码什么都不做。这就是 gets
命令的作用。
我需要的是 gets
命令的替代方法,比如 coolget
。 coolget
命令不应该等待回车按钮,而是注册一些当它被点击时调用的插槽,然后继续执行。所需的代码应如下所示:
proc evaluate { string } \
{
catch { eval $string } got
if { $got ne "" } {
puts stderr $got
}
}
puts -nonewline stdout "MyShell > "
flush stdout
coolgets stdin evaluate; # this command should not wait for the enter button
# here goes some code which is to be executed before the enter button is hit
这是我需要的:
proc prompt { } \
{
puts -nonewline stdout "MyShell > "
flush stdout
}
proc process { } \
{
catch { uplevel #0 [gets stdin] } got
if { $got ne "" } {
puts stderr $got
flush stderr
}
prompt
}
fileevent stdin readable process
prompt
while { true } { update; after 100 }
最佳答案
我认为您需要查看 fileevent、fconfigure 和 vwait 命令。使用这些,您可以执行以下操作:
proc GetData {chan} {
if {[gets $chan line] >= 0} {
puts -nonewline "Read data: "
puts $line
}
}
fconfigure stdin -blocking 0 -buffering line -translation crlf
fileevent stdin readable [list GetData stdin]
vwait x
此代码将 GetData 注册为 stdin 的可读文件事件处理程序,因此只要有数据可供读取,它就会被调用。
关于TCL 获取带有某种 -nohang 选项的命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8719899/