【问题标题】:How can I suppress the output messages of TCL procedures?如何抑制 TCL 程序的输出信息?
【发布时间】:2014-09-17 18:08:50
【问题描述】:

在我的 TCL 脚本中,我使用了几个我没有源代码的程序。所有这些程序都执行一些任务并输出大量消息。但我只想完成任务,我想压制消息。有没有办法做到这一点。

例如,我想像这样运行一个程序:

my_proc $arg1 $arg2 $arg3

并抑制它的所有消息。任何解决方法/智能替代方案都值得赞赏。

更多信息:我正在使用一个自定义 shell,它将 TCL 文件作为参数并运行它。在这个自定义 shell 中,我可以访问一些我没有代码的 TCL 程序。

甚至有什么方法可以让脚本的输出转到文件而不是命令提示符 (stdout)?

【问题讨论】:

  • 你能做到吗:set output [my_proc $args]
  • @Glenn 我试过了,它仍然可以打印东西。我认为 proc 代码中有一堆我无权访问的 puts 语句。
  • 我在考虑我认为的外壳。我的评论很愚蠢。

标签: tcl


【解决方案1】:

尝试在您的代码中更改puts

rename ::puts ::tcl_puts
proc puts args {}        ;# do nothing

然后,如果你想打印一些东西,使用tcl_puts

这有点像核选项。你可以变得更微妙:

proc puts args {
    if {[llength $args] == 1} {
        set msg [lindex $args 0]
        # here you can filter based on the content, or just ignore it
        # ...
    } else {
        # in the 2a\-args case, it's file io, let that go
        # otherwise, it's an error "too many args"
        # let Tcl handle it
        tcl_puts {*}$args

        # should probably to stuff there so that errors look like
        # they're coming from "puts", not "tcl_puts"
    }
}

另一个想法:只需在您调用的命令期间执行此操作:

proc noputs {args} {
    rename ::puts ::tcl_puts
    proc ::puts args {}

    uplevel 1 $args

    rename ::puts ""
    rename ::tcl_puts ::puts
}

noputs my_proc $arg1 $arg2 $arg3

演示:

$ tclsh
% proc noputs {args} {
    rename ::puts ::tcl_puts
    proc ::puts args {}

    uplevel 1 $args

    rename ::puts ""
    rename ::tcl_puts ::puts
}
% proc my_proc {foo bar baz} {
    lappend ::my_proc_invocations [list $foo $bar $baz]
    puts "in myproc with: $foo $bar $baz"
}
% my_proc 1 2 3
in myproc with: 1 2 3
% noputs my_proc a b c
% my_proc x y z
in myproc with: x y z
% set my_proc_invocations
{1 2 3} {a b c} {x y z}

【讨论】:

  • 在 8.6 中使用 tryfinally 的好人选
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-05
  • 2018-02-02
  • 1970-01-01
  • 2018-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多