How to check if stdin is readable in TCL?

丶灬走出姿态 提交于 2019-12-11 11:51:30

问题


With the following command you can register some callback for stdin:

fileevent stdin readable thatCallback

This means that during the execution of the update command it will evaluate thatCallback time after time while there is input available at stdin.

How can I check if input is available at stdin ?


回答1:


You simply read/gets from stdin inside your callback. Basically the pattern goes like this snippet from the fileevent example from Kevin Kenny:

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



回答2:


If you look at the answer to this question you can see how to use fconfigure to put the channel into non-blocking mode. There is a lot more detailed information on this Tcl manual, you need to look at the fconfigure manual page together with the vwait manual page.



来源:https://stackoverflow.com/questions/8747652/how-to-check-if-stdin-is-readable-in-tcl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!