Tk, tcl exec stderr, stdout separately

I have a tcl script.

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

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

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

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

I would also like to get the result for a variable.

Thanks in advance...

+3
source share
2 answers

If you open the command as a channel 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}"
+3
source

Use 2> to redirect stderr:

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

Then you can 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"
+1
source

Source: https://habr.com/ru/post/1721015/


All Articles