【发布时间】:2012-02-03 13:57:13
【问题描述】:
使用以下命令可以为stdin注册一些回调:
fileevent stdin readable thatCallback
这意味着在执行更新命令期间,当stdin 有可用输入时,它将一次又一次地评估thatCallback。
如何检查stdin 的输入是否可用?
【问题讨论】:
使用以下命令可以为stdin注册一些回调:
fileevent stdin readable thatCallback
这意味着在执行更新命令期间,当stdin 有可用输入时,它将一次又一次地评估thatCallback。
如何检查stdin 的输入是否可用?
【问题讨论】:
您只需在回调中从标准输入读取/获取。基本上这个模式就像来自fileevent example from Kevin Kenny的sn-p:
proc isReadable { f } {
# The channel is readable; try to read it.
set status [catch { gets $f line } result]
if { $status != 0 } {
# Error on the channel
puts "error reading $f: $result"
set ::DONE 2
} elseif { $result >= 0 } {
# Successfully read the channel
puts "got: $line"
} elseif { [eof $f] } {
# End of file on the channel
puts "end of file"
set ::DONE 1
} elseif { [fblocked $f] } {
# Read blocked. Just return
} else {
# Something else
puts "can't happen"
set ::DONE 3
}
}
# Open a pipe
set fid [open "|ls"]
# Set up to deliver file events on the pipe
fconfigure $fid -blocking false
fileevent $fid readable [list isReadable $fid]
# Launch the event loop and wait for the file events to finish
vwait ::DONE
# Close the pipe
close $fid
【讨论】:
stdin 提供了一个输入,我想读取该输入。我可以使用gets 命令逐行读取它,但最后一个gets 将挂起并等待输入。上面的代码也是同样的情况。
gets 以负值成功但eof 和fblocked 都是错误的。我认为其他问题案例要么直接在 IO 库中处理,要么反映为来自 gets 的错误。
fconfigure -blocking false 则gets 不会挂起。但在这种情况下,如果输入不以换行符结尾,则不会读取输入的最后一部分(从最后一个换行到输入结尾的部分)。这产生了另一个问题:stackoverflow.com/questions/8750139/…
如果您查看this 问题的答案,您可以了解如何使用 fconfigure 将通道置于非阻塞模式。这个 Tcl 手册有很多更详细的信息,你需要同时查看 fconfigure 手册页和 vwait 手册页。
【讨论】: