2009-10-25 155 views
3

我有一个tcl脚本。tk,tcl exec stderr,stdout分开

问题是我必须调用一个脚本,可以写一些东西给stderr(这不是关键故障)。

我想在tk/tcl中分别捕获stderr和stdout。

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

此代码将返回我的结果,但它也包含stderr。

此外,我想得到的结果变量。

在此先感谢...

+0

小问题:在代码示例中包含方括号。 +1为一个伟大的问题! – 2015-06-04 13:33:55

回答

3

如果你打开该命令作为管道而不是使用exec,则可以分隔标准输出和标准错误。请参阅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}" 
+0

谢谢...得到它的工作方式... – Egon 2009-10-26 12:33:11

1

使用2>重定向标准错误:

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

然后,您可以读取error.txt的内容:

package require Tclx; # Needed for the read_file command 
set err [read_file error.txt] 
puts "s1: err = $err" 
+0

我希望能够直接将它变成没有临时文件的变量。我知道这是可能的,但我真的不喜欢临时文件。 – Egon 2009-10-26 06:27:50