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

  1. namespace eval subprocess {
  2.  
  3. # this will be set to 1 when the subprocess has finished
  4. variable finished 0
  5.  
  6. # here we can save the output of the subprocess
  7. variable output {}
  8.  
  9. proc handledata {f} {
  10. variable finished
  11. variable output
  12. if {[eof $f]} {
  13. set finished 1
  14. } else {
  15. set x [read $f]
  16. puts -nonewline $x
  17. append output $x
  18. }
  19. }
  20.  
  21.  
  22. proc run {cmd} {
  23. variable finished
  24. set finished 0
  25. variable output
  26. set output {}
  27.  
  28. fconfigure stdout -buffering none
  29. set f [open |$cmd]
  30.  
  31.  
  32. # -buffering none ensures we can read output char by char, instead of line by line
  33. # line by line reading may require -translation to be set
  34. fconfigure $f -buffering none -blocking 0
  35.  
  36. fileevent $f readable [list [namespace current]::handledata $f]
  37. # vwait waits for the named variable to change
  38. vwait [namespace current]::finished
  39. close $f
  40. }
  41. }
  42.  
  43.  
  44. set cmd ./try.sh
  45.  
  46. puts "Opening $cmd"
  47. ::subprocess::run $cmd
  48. puts "Finished! Output was '$::subprocess::output'"