【问题标题】:reading a buffer stream in tcl在 tcl 中读取缓冲流
【发布时间】:2012-09-07 14:59:40
【问题描述】:

这是一个关于在 tcl 中读取文件的问题。 我正在打开一个要写入的缓冲区流,并且我只有一个文件处理程序引用它 现在,在逐行读取此缓冲区时,在某些情况下,我必须将缓冲区的所有内容都放入,请建议我如何实现这一点。 所以我只是粘贴一个示例代码来解释我的要求。

catch { open "| grep" r } pipe
while { [gets $pipe line] } {
      if { some_condition } {
          ## display all the content of $pipe as string
      }
}

谢谢 汝驰

【问题讨论】:

    标签: tcl file-handling


    【解决方案1】:

    要从管道读取直到它被另一端关闭,只需使用read $pipe。然后让你这样做:

    set pipe [open "| grep" r]
    while { [gets $pipe line] >= 0 } {  # zero is an empty line...
        if { some_condition } {
            puts [read $pipe]
            ### Or, to include the current line:
            # puts $line\n[read $pipe]
        }
    }
    

    如果您想要管道输出中之前的任何内容,则必须将其保存在变量中。

    【讨论】:

    • 我还建议不要像问题中那样在open |... 周围加上catch,因为您收到的错误消息永远不是有效的频道名称。
    • 另外应该注意的是,GNU grep 默认使用完全缓冲,所以如果它真的打算逐行读取其输出,建议将--line-buffered 命令行选项传递给它。不确定其他 grep 实现。
    猜你喜欢
    • 1970-01-01
    • 2012-01-25
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多