正确的错误处理 EXPECT / TCL

Proper Error handling EXPECT / TCL

防止向死进程发送命令的最佳方法是什么?

有时我的会话在应该打开时被终止,所以我最终发送命令并收到错误:

send: spawn id exp4 not open

我正在尝试做类似

的事情
if [catch send "test\r"] {
      puts "send error!"
}

但似乎查询每次都为真。

这是最简单的例子,但我有更复杂的 "send / expects",我使用捕获组等,所以在每个 "send / expect" 周围放置一个 catch 或创建一个函数似乎并不有用。

你能用 catch 包裹整个程序吗?捕获此类错误的正确方法是什么?

Expect 作者写了一个 FAQ 来解决这个问题:http://expect.sourceforge.net/FAQ.html#q64

看来你想要这样的东西

expect_before {
    eof { respawning_the_process }
}

我确定有一些问题需要解决(比如当流程应该结束时该怎么做)

这个问题:

if [catch send "test\r"] {

是双重的:

  1. 你没有用大括号括住条件,所以它没有在正确的时间得到评估。
  2. 您没有为 catch 命令提供正确的参数

你会想写:

if {[catch {send "test\r"} output] != 0} {

这个可以抽象成proc

proc send {args} {
    set status [catch [list exp_send {*}$args] output]
    # error handling if $status is non-zero
}

"exp_send" 是 expect "send" 命令的内置别名,因此可以安全地使用 proc 覆盖 "send",从而最大限度地减少所需的代码更改量。