tags:

views:

534

answers:

2

I have a tcl script.

The problem is that I have to call a script that can write something to stderr (it's not a critical failure).

I would like to capture stderr and stdout separately in tk/tcl.

if { [catch {exec "./script.sh" << $data } result } {
   puts "$::errorInfo"
}

This code will return my result but it also contains stderr.

Also I would like to get the result to a variable.

Thanks in advance...

+1  A: 

Use the 2> to redirect stderr:

if { [catch {exec "./script.sh" << $data 2> error.txt} result } {
   puts "$::errorInfo"
}

You can then read the contents of error.txt:

package require Tclx; # Needed for the read_file command
set err [read_file error.txt]
puts "s1: err = $err"
Hai Vu
I was hoping to get it directly into a variable without temporary files. I knew it was possible this way but I really don't like temp files.
egon
+1  A: 

If you open the command as a pipe instead of using exec, you can separate stdout and stderr. See http://wiki.tcl.tk/close

set data {here is some data}
set command {sh -c {
    echo "to stdout"
    read line
    echo "$line"
    echo >&2 "to stderr"
    exit 42
}}
set pipe [open "| $command" w+]
puts $pipe $data
flush $pipe
set standard_output [read -nonewline $pipe]
set exit_status 0
if {[catch {close $pipe} standard_error] != 0} {
    global errorCode
    if {"CHILDSTATUS" == [lindex $errorCode 0]} {
        set exit_status [lindex $errorCode 2]
    }
}
puts "exit status is $exit_status"
puts "captured standard output: {$standard_output}"
puts "captured standard error: {$standard_error}"
glenn jackman
thanks... got it working that way...
egon