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

# shell script to test with:
#
# #!/bin/sh
# i=9
# while [ "$i" -gt 0 ]; do
#   echo -n $i
#   sleep 1
#   i=$((i-1))
# done
# echo "!"


set cmd ./try.sh

fconfigure stdout -buffering none
puts "Opening $cmd"
set f [open |$cmd]

# this will be set to 1 when the subprocess has finished
variable finished 0

# -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 handledata $f]

proc handledata {f} {
    variable finished
    if {[eof $f]} {
        set finished 1
    } else {
        set x [read $f]
        puts -nonewline $x
    }
}

# vwait waits for the named variable to change
vwait finished
close $f
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'"