try-catch - 在 TCL catch 命令中捕获标准输出

标签 try-catch tcl catch-block

在我的主 tcl 脚本中,我正在调用包含在 catch 命令中的 tcl 过程。 该过程又调用另外 10 个过程。

当这 10 个进程中的任何一个执行时出现错误时,TCL 仍然按预期继续执行我的主脚本,我只能查看捕获的错误消息。此错误消息可能/可能不足以确定 10 个过程中哪一个在执行过程中出错。

有没有办法继续捕获所有标准输出,直到出现错误为止? 我知道可以通过将这 10 个过程中的所有消息(puts 语句)写入另一个日志文件来完成。但我很想知道是否还有其他方法。

最佳答案

catch 命令根本不拦截 I/O。要拦截输出,最简单、最有效的方法是输入 channel transform在该 channel 上使用 chan Push

oo::class create Capture {
    variable contents encoding
    # Implement the channel interception protocol
    method initialize {handle mode} {
        set contents {}
        return {initialize finalize write}
    }   
    method finalize handle {
        # We do nothing here
    }
    method write {handle buffer} {
        append contents $buffer
        return $buffer
    }

    # Methods for ordinary people!
    method capture {channel body} {
        set encoding [chan configure $channel -encoding]
        chan push $channel [self]
        try {
            uplevel 1 $body
        } finally {
            chan pop $channel
        }
    }
    method contents {} {
        # Careful; need the encoding as channels work with binary data
        return [encoding convertfrom $encoding $contents]
    }
}

如何使用该类:

set capt [Capture new]
$capt capture stdout {
    puts "Hello world!"
}
puts "Captured [string length [$capt contents]] characters"
puts [lmap c [split [$capt contents] ""] {scan $c "%c"}]

输出(我假设您识别 ASCII 代码;末尾的 13 10 是回车/换行序列):

Hello world!
Captured 14 characters
72 101 108 108 111 32 119 111 114 108 100 33 13 10

关于try-catch - 在 TCL catch 命令中捕获标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64547745/

相关文章:

java - catch block 中的语句未执行

c# - 在 catch block 内运行时检测

java catch block 导致多个输出

powershell - 如何从 PowerShell 脚本中获取退出代码

java - java同一个类中多个方法中try catch的常用代码

regex - 如何使用 Tcl 正则表达式提取所有匹配项?

variables - tcl 中的变量作用域

c++ - 包括用于 C/C++ 的 expect/tcl 库

java - 发生异常时如何继续批量插入

c# - 如何使用超时进行 try-catch?