问题描述
|
我想用相同名称和调用约定的proc替换\“ proc N \”的定义,但要添加一些额外的错误检测代码。
在python中,我可以做下面想要的事情,但是我对名称空间和函数在tcl中的处理方式一无所知。
__orig_N = N
def N(arg1,arg2):
if arg1 != \'GOOD VALUE\':
exit(\'arg1 is bad\')
return __orig_N(arg1,arg2)
解决方法
Tcl对程序有很好的自省。这使您可以重写一个过程以添加更多代码:
# Assume there are no defaults; defaults make this more complicated...
proc N [info args N] [concat {
# Use \'ne\' for string comparison,\'!=\' for numeric comparison
if {$arg1 ne \"GOOD VALUE\"} {
error \"arg1 is bad\"
# The semicolon is _important_ because of the odd semantics of [concat]
};
} [info body N]]
好的,这不是唯一的方法-Eric的答案更接近于我通常包装命令的方式,并且它也具有处理非过程命令的优势-但是这种解决方案具有将代码紧密绑定的优点,因此以后几乎不会出错。它还不会在任何错误跟踪中引入额外的堆栈帧,从而有助于简化调试。
,您可以使用rename
命令重命名现有的proc:
rename N __orig_N
proc N {arg1 arg2} {
if { $arg1 != \"GOOD_VALUE\" } {
puts stderr \"arg1 is bad\"
exit 1
}
return [uplevel 1 __orig_N $arg1 $arg2]
}
实际上,这比python原始代码要复杂一些,因为使用uplevel
可以有效地将整个包装从调用堆栈中剔除-诚然,在您的情况下,这不是必需的,但是很高兴能够去做吧。