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

编程入门 行业动态 更新时间:2024-10-16 23:22:53
本文介绍了在 TCL catch 命令中捕获标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在我的主 tcl 脚本中,我调用了一个包含在 catch 命令中的 tcl proc.这个 proc 又调用了 10 个以上的 proc.

In my main tcl script, I am calling a tcl proc wrapped in a catch command. This proc in-turn calls 10 more procs.

当这 10 个 proc 中的任何一个执行错误时,TCL 仍会按预期继续执行我的主脚本,我只能查看我捕获的错误消息.此错误消息可能/可能不具有决定性,足以确定 10 个 proc 中的哪一个在执行期间出错.

When there is an error in execution in any of those 10 procs, TCL still continues execution of my main script as expected and I am just able to view the error message which I captured. This error message may/may-not be conclusive enough to determine which of the 10 procs errored out during execution.

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

Is there a way to still keep capturing all the stdout until the point of error? I know it can be done by writing all messages (puts statements) in those 10 procs to another log file. But I'm interested in knowing if there is any other way.

推荐答案

catch 命令根本不拦截 I/O.拦截输出,最简单也是最多的方法就是放一个channel使用 chan push 在该频道上转换.

The catch command doesn't intercept I/O at all. To intercept output, the simplest and most method is to put a channel transform on that channel with 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 是一个回车/换行序列):

Output (I assume you recognise ASCII codes; the 13 10 at the end is a carriage-return/new-line sequence):

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

这篇关于在 TCL catch 命令中捕获标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 09:30:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1407723.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:命令   标准   TCL   catch

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!