【问题标题】:Tcl redirect stdout to file produces no outputTcl 将标准输出重定向到文件不产生输出
【发布时间】:2021-09-09 07:10:30
【问题描述】:

问题是link 中回答的内容的扩展。在尝试使用它延迟打印输出时,shell 上的cat file_name 不会在使用after 的延迟时间内显示文件的内容。代码如下:

proc foo {times} { 
    while {$times >0} {
        puts "hello$times"
        incr times -1
        after 20000
        puts "hello world" 
    }
}
proc reopenStdout {file} {
    close stdout
    open $file w        ;# The standard channels are special
}

reopenStdout ./bar
foo 10

【问题讨论】:

    标签: tcl stdout


    【解决方案1】:

    您正在写入的数据正在内存中缓冲,而您写入的数据不足以将内部缓冲区刷新到磁盘。在foo 的循环内添加flush stdout,或执行类似设置新打开的通道为行缓冲的操作:

    proc reopenStdout {file} {
        close stdout
        set ch [open $file w]        ;# The standard channels are special
        chan configure $ch -buffering line
    }
    

    如果行缓冲不够,您可以使用chan configure 的-buffering and -buffersize 选项来获得最适合您需要的行为。

    【讨论】:

    • 是的,我也这么认为,但是为什么原始答案中的puts "hello world" 不需要刷新?那是因为程序/脚本已结束并完成了自动刷新吗?
    • @almostacoder 通道在关闭时刷新,是的(显式或退出时)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 2015-05-23
    • 1970-01-01
    相关资源
    最近更新 更多