Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to track a log file in TCL

Say there is a file log.txt and some kind of log is being appended to it permanently.

I want to track that file in the TCL environment.

I have tried this but it didn't worked.

set log [open log.txt a]

for { } { true } { update; after 1000 } {

    # expected to get here the appended part
    read $log

    seek $log 0 end

}

Is it possible to read the modified file by the same file handle log, or I have to close and re-open the file log.txt ?

Is there a kind of equivalent of Linux command tail -f in TCL ?

like image 547
Vahagn Avatar asked Nov 28 '11 21:11

Vahagn


People also ask

How do I read a file from a directory in Tcl?

-- reading a file. The Tcl file commands are file, open, close, gets and read, and puts, seek, tell, and eof, fblocked, fconfigure, Tcl_StandardChannels(3), flush, fileevent, filename. One way to get file data in Tcl is to 'slurp' up the file into a text variable.

What is file handling in Tcl?

Tcl supports file handling with the help of the built in commands open, read, puts, gets, and close. A file represents a sequence of bytes, does not matter if it is a text file or binary file.

How do I run a file in Tcl?

When you have installed Tcl, the program you will then call to utilize it is tclsh . For instance, if you write some code to a file "hello. tcl", and you want to execute it, you would do it like so: tclsh hello.

How do I run a Tcl file from the command line?

You can run this program by starting tclsh from the start menu, then typing the command source c:/hello. tcl.


1 Answers

Just use tail. It knows more that you about how to handle complicated cases (you can look at its source).

In one of my projects, I have something like this to monitor a trace file produced by a proprietary tool:

set fd [open [list | tail --follow=name --retry --lines 0 $opt(trace) 2>@1]]
chan event $fd readable [list FollowTrace $fd]

proc FollowTrace fd {
  if {[gets $fd line] < 0} {
    set code [catch {close $fd} err]
    if {$code == 0} {
      set ::result 0
    } else {
      puts stderr $err
      set ::result 1
    }
    return
  }

  switch -regexp -matchvar parts -- $line {
    {Tm_Session::Open.*FileName=([^,]+)} {
       TryMakeLock [FullPathname [lindex $parts 1]]
     }
     {Tm_Session::Close.*FileName=([^,]+)} {
        StartUpload [lindex $parts 1]
     }
  }
}

The general idea is that you spawn tail on a given file then enter event loop and process tail's output line-by-line.

like image 148
kostix Avatar answered Sep 25 '22 06:09

kostix