Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tk, tcl exec stderr, stdout separately

Tags:

scripting

tk

tcl

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...

like image 763
Egon Avatar asked Oct 25 '09 15:10

Egon


2 Answers

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}"
like image 126
glenn jackman Avatar answered Sep 22 '22 02:09

glenn jackman


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"
like image 39
Hai Vu Avatar answered Sep 22 '22 02:09

Hai Vu