我有以下步骤:
proc show_information {args} {
set mandatory_args {
-tftp_server
-device ANY
-interface ANY
}
set optional_args {
-vlan ANY
}
parse_dashed_args -args $args -optional_args $optional_args -mandatory_args $mandatory_args
log -info "Logged in device is: $device"
log -info "Executing proc to get all data"
set commands {
"show mpls ldp neighbor"
"show mpls discovery vpn"
"show mpls interface"
"show mpls ip binding"
"show running-config"
"show policy-map interface $intr vlan $vlan input"
"show run interface $intr
}
foreach command $commands {
set show [$device exec $command]
ats_log -info $show
}
}
我是tcl的新手,并且想知道如果传递错误的参数或错误输出,如何处理错误。
诸如python的尝试*(执行proc),而*(在失败的情况下打印一些msg)除外。
经过一番谷歌搜索后,TCL中使用了“catch”,但无法弄清楚如何使用它。
最佳答案
catch
命令运行脚本并捕获其中的任何失败。该命令的结果实际上是一个 bool(boolean) 值,用于描述是否发生错误(实际上是一个结果代码,但是0是成功,1是错误;还有其他一些,但是您通常不会遇到它们)。您还可以给变量放置“结果”,这是成功时的正常结果,失败时的错误消息。
set code [catch {
DoSomethingThat mightFail here
} result]
if {$code == 0} {
puts "Result was $result"
} elseif {$code == 1} {
puts "Error happened with message: $result"
} else {
# Consult the manual for the other cases if you care
puts "Code: $code\nResult:$result"
}
在许多简单的情况下,您可以将其缩短为:
if {[catch {
DoSomethingThat mightFail here
} result]} {
# Handle the error
} else {
# Use the result
}
Tcl 8.6添加了新命令来处理错误。
try
命令与您使用Python时更像:try {
DoSomethingThat mightFail here
} on error {msg} {
# Handle the error
}
它还支持
finally
和trap
子句,以分别确保操作和更复杂的错误处理。例如(用catch
编写的代码很烦人):try {
DoSomethingThat mightFail here
} trap POSIX {msg} {
# Handle an error from the operating system
}
关于error-handling - TCL中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43198502/