Posted to tcl by aspect at Fri Jun 18 00:53:18 GMT 2010view raw

  1. # shell script to test with:
  2. #
  3. # #!/bin/sh
  4. # i=9
  5. # while [ "$i" -gt 0 ]; do
  6. # echo -n $i
  7. # sleep 1
  8. # i=$((i-1))
  9. # done
  10. # echo "!"
  11.  
  12.  
  13. set cmd ./try.sh
  14.  
  15. fconfigure stdout -buffering none
  16. puts "Opening $cmd"
  17. set f [open |$cmd]
  18.  
  19. # this will be set to 1 when the subprocess has finished
  20. variable finished 0
  21.  
  22. # -buffering none ensures we can read output char by char, instead of line by line
  23. # line by line reading may require -translation to be set
  24. fconfigure $f -buffering none -blocking 0
  25.  
  26. fileevent $f readable [list handledata $f]
  27.  
  28. proc handledata {f} {
  29. variable finished
  30. if {[eof $f]} {
  31. set finished 1
  32. } else {
  33. set x [read $f]
  34. puts -nonewline $x
  35. }
  36. }
  37.  
  38. # vwait waits for the named variable to change
  39. vwait finished
  40. close $f
  41. puts "process exited: $cmd"

Comments

Posted by aspect at Fri Jun 18 01:00:23 GMT 2010 [text] [code]

namespace eval subprocess { # this will be set to 1 when the subprocess has finished variable finished 0 # here we can save the output of the subprocess variable output {} proc handledata {f} { variable finished variable output if {[eof $f]} { set finished 1 } else { set x [read $f] puts -nonewline $x append output $x } } proc run {cmd} { variable finished set finished 0 variable output set output {} fconfigure stdout -buffering none set f [open |$cmd] # -buffering none ensures we can read output char by char, instead of line by line # line by line reading may require -translation to be set fconfigure $f -buffering none -blocking 0 fileevent $f readable [list [namespace current]::handledata $f] # vwait waits for the named variable to change vwait [namespace current]::finished close $f } } set cmd ./try.sh puts "Opening $cmd" ::subprocess::run $cmd puts "Finished! Output was '$::subprocess::output'"