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

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'"