期望 -re 不会在 eof 上失败

Expect -re not failing on eof

我有以下 expect 脚本。

这是test.exp

#!/usr/bin/expect

# exp_internal 1
# log_file -noappend ~/expect.log

# Use `send_log` to print to log file

set timeout 30

set bold [exec tput bold]
set red [exec tput setaf 1]
set green [exec tput setaf 2]
set normal [exec tput sgr0]

proc test_label {value} {
  upvar bold bold
  upvar normal normal
  puts "Running ${bold}${value}${normal}…"
}
proc test_send {value} {
  sleep 0.1
  send "$value"
}
proc test_failed {} {
  upvar bold bold
  upvar red red
  upvar normal normal
  sleep 0.1
  puts "${bold}${red}Failed${normal}"
  exit 1
}
proc test_ok {{force_close false}} {
  upvar bold bold
  upvar green green
  upvar normal normal
  sleep 0.1
  puts "${bold}${green}OK${normal}"
  if {$force_close} {
    close
  }
}

expect_before {
  default {
    test_failed
  }
}

这是electrum.exp

#!/usr/bin/expect

source ./test.exp

test_label "Should create Electrum mnemonic"

spawn qr-backup.sh --create-electrum-mnemonic

expect {
  -re {Format USB flash drive \(y or n\)\?} {
    test_send "n\r"
  }
}

expect {
  -re {\[sudo\] password for pi:} {
    test_send "$env(password)\r"
  }
}

expect {
  -re {Creating Electrum mnemonic…}
}

expect {
  -re {([a-z]+ ?){24}} {
    test_ok true
  }
}

为什么当 spawn qr-backup.sh --create-electrum-mnemonic 返回的最后一行是 electrum: error: unrecognized arguments: --nbits 264 时脚本不会失败?

想通了!

使用 eof 语句解决。

expect {
  -re {([a-z]+ ?){24}} {
    test_ok true
  }
  eof {
    test_failed
  }
}

请注意 expect 手册页中的这一点:

expect_before [expect_args]

Unless overridden by a -i flag, expect_before patterns match against the spawn id defined at the time that the expect_before command was executed (not when its pattern is matched).

(强调我的)

执行 expect_before 命令时没有生成 ID 处于活动状态。