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...
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}"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With