简体   繁体   中英

TCL - How to print on the screen th messages that where printed during execution of exec command?

Say I have want to execute a script or and executable file by printing runtime the output of execution.

When I do:

set log [exec ./executable_file]
puts $log

Then it waits a long time and then prints everything at once. But I want runtime printing. How can I do this?

Not perfect (as it require writing to external file):

set log [exec executable_file | tee log.txt >@stdout]

The output will be displayed immediately, at the same time, saved to 'log.txt'. If you don't care about saving the output:

set log [exec executable_file >@stdout]

Use open "| ..." and asyncronous linewise reading from the returned descriptor, like this:

proc ReadLine fd {
  if {[gets $fd line] < 0} {
    if {[chan eof $fd]} {
      chan close $fd
      set ::forever now
      return
    }
  }
  puts $line
}

set fd [open "| ./executable_file"]
chan configure $fd -blocking no
chan event $fd readable [list ReadLine $fd]

vwait forever

See this wiki page for more involved examples.

In a real program you will probably already have an event loop running so there would be no need for a vwait specific to reading the output of one command.

Also if you need to collect the output, not just [puts] each line after it has been read, you will pobably need to create a global (usually namespaced) variable, initialize it to "", pass its name as another argument to the callback procedure ( ReadLine here) and append the line to that variable's value.

也许你可以在可执行文件之前在后台启动另一个进程,比如tail -f logfile.txt,并在这个logfile.txt中输出你的可执行文件的结果?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM