Posted to tcl by APN at Wed Sep 01 18:21:25 GMT 2010view pretty

################################################################
# Command line loop

# Asynch command line adapted from Welch.
# Reads commands from standard input and executes them.
proc ::woof::console::start {{prompt "woof>"}} {
    variable command_line
    set command_line ""
    puts -nonewline $prompt
    flush stdout
    fileevent stdin readable [list [namespace current]::run_command $prompt]
}

# Callback from file event to execute a command
proc ::woof::console::run_command {prompt} {
    variable command_line

    if {[eof stdin]} { exit }
    
    append command_line [gets stdin]
    if {[info complete $command_line]} {
        
        if {[catch {uplevel \#0 $command_line} result]} {
            set chan stderr
        } else {
            set chan stdout
        }
        set command_line ""
        puts $chan $result
        flush $chan
        puts -nonewline $prompt
        flush stdout
    } else {
        # Command not complete
        append command_line "\n"
    }
    return
}


# Stops the command line loop
proc ::woof::console::stop {} {
    variable command_line
    set command_line ""
    fileevent stdin readable {}
}

::woof::console::start
vwait ::until_exit