【问题标题】:How to print newly updated lines in tcl如何在 tcl 中打印新更新的行
【发布时间】:2015-04-08 18:06:10
【问题描述】:

我需要打印文件中新添加的行。 我的代码如下所示:

proc dd {} {
    global line_number
    set line_number 0
    set a [open "pkg.v" r]
    #global count
    while {[gets $a line]>=0} {
        incr line_number
        global count
        set count [.fr.lst2 size]
        puts "enter $count"
        if {[eof $a]} {
            #.fr.lst2 insert end "$line"
            # set count [.fr.lst2 size]
            close $a
        } elseif {$count > 0} {
            .fr.lst2 delete 0 end
            if {$count+1} {
                .fr.lst2 insert end "$line"
                puts "i am $count"
            }
        } else {
            .fr.lst2 insert end "$line"
            puts "i am not"
        }
    }
    puts "$count"
}

【问题讨论】:

  • 我们是在讨论最后添加的行吗?还是中间插入的线?我们是在 Windows 还是其他平台上?
  • 由于您循环文件行的惯用方式,[eof $a] 在 while 循环中永远不会为真——eofprevious 时返回真i> 文件读取命中文件结尾,此时,while 条件已经停止循环。

标签: tcl


【解决方案1】:

假设我们正在讨论写入任何 Unix 系统(Linux、OSX 等)上日志文件末尾的行,那么在 tail 的帮助下可以轻松完成:

# Make the pipeline to read from 'tail -f'; easy easy stuff!
set mypipe [exec |[list tail -f $theLogfile]]
# Make the pipe be non-blocking; usually a good idea for anything advanced
fconfigure $mypipe -blocking 0
# Handle data being available by calling a procedure which will read it
# The procedure takes two arguments, and we use [list] to build the callback
# script itself (Good Practice in Tcl coding)
fileevent $mypipe readable [list processLine $mypipe .fr.lst2]

proc processLine {pipeline widget} {
    if {[gets $pipeline line] >= 0} {
        # This is probably too simplistic for you; adapt as necessary
        $widget insert end $line
    } elseif {[eof $pipeline]} { # Check for EOF *after* [gets] fails!
        close $pipeline
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多