我有一个将列表打印为格式化表格的过程。它有像 print_table $temp 这样的用例
我如何给出不同过程的输出,其中我使用“puts”命令打印输出作为该过程 print_table 的输入?
set list1 {{abc 1} {defg 2} {hijlk 3} {lmn 4}}
proc abc { list1 } {
foreach lst $list1 {
puts "$lst"
}
}
> abc $list1
abc 1
defg 2
hijlk 3
lmn 4
> print_table $list1
==============
| abc | 1 |
| defg | 2 |
| hijlk | 3 |
| lmn | 4 |
==============
我想让下面的工作
> print_table [abc $list1]
==============
| abc | 1 |
| defg | 2 |
| hijlk | 3 |
| lmn | 4 |
==============
正如 Donal 指出的,最好让打印代码使用通道作为参数。或者,如果您无法控制所有打印过程,或者您不想接触它们,则可以使用通道拦截器(之前介绍过,例如捕获 Tcl 测试套件输出 https://stackoverflow.com/questions/49728794/redirect-test-results-for-tcltest/49730358#49730358):
通道拦截器被实现为通道变换;并已被覆盖here https://stackoverflow.com/questions/14530354/stdout-redirection/14538125#14538125前。
第 1 步:定义通道拦截器
oo::class create ChannelSink {
variable buffer
method initialize {handle mode} {
if {$mode ne "write"} {error "can't handle reading"}
return {finalize initialize write}
}
method finalize {handle} {
# NOOP
}
method write {handle bytes} {
append buffer $bytes
return $bytes
}
method getCapture {} {
set r $buffer
unset buffer
return $r
}
}
上面的代码片段是直接源自/窃取的Donal https://stackoverflow.com/questions/14530354/stdout-redirection/14538125#14538125.
第2步:注册拦截器stdout
围绕你的打印代码
set cs [ChannelSink new]
chan push stdout $cs
abc $list1
chan pop stdout
print_table [$cs getCapture]
您可以将拦截样板打包到print_table
,使其看起来像:print_table {abc $list1}
.
proc print_table {script} {
# set up interception
uplevel 1 $script
# remove interception
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)