【问题标题】:How to check if stdin is readable in TCL?如何检查标准输入在 TCL 中是否可读?
【发布时间】:2012-02-03 13:57:13
【问题描述】:

使用以下命令可以为stdin注册一些回调:

fileevent stdin readable thatCallback

这意味着在执行更新命令期间,当stdin 有可用输入时,它将一次又一次地评估thatCallback。

如何检查stdin 的输入是否可用?

【问题讨论】:

    标签: tcl stdin gets readable


    【解决方案1】:

    您只需在回调中从标准输入读取/获取。基本上这个模式就像来自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 将挂起并等待输入。上面的代码也是同样的情况。
    • 不,重要的是'fconfigure -blocking false'。
    • 我不认为在任何情况下gets 以负值成功但eof 和fblocked 都是错误的。我认为其他问题案例要么直接在 IO 库中处理,要么反映为来自 gets 的错误。
    • 好的。如果fconfigure -blocking false 则gets 不会挂起。但在这种情况下,如果输入不以换行符结尾,则不会读取输入的最后一部分(从最后一个换行到输入结尾的部分)。这产生了另一个问题:stackoverflow.com/questions/8750139/…
    【解决方案2】:

    如果您查看this 问题的答案,您可以了解如何使用 fconfigure 将通道置于非阻塞模式。这个 Tcl 手册有很多更详细的信息,你需要同时查看 fconfigure 手册页和 vwait 手册页。

    【讨论】:

      猜你喜欢
      • 2012-02-04
      • 2012-02-03
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多