在我的主 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/