我有这个代码启动一个进程,expect
一些启动输出,然后将其余的记录到文件中:
proc foo { } {
set log_fp [open "somefile" a]
exec cp $prog "$prog.elf"
spawn someprog
set someprog_spawn_id $spawn_id
# do some things here that that wait for output from someprog
expect {
-i $someprog_spawn_id
-re "Some output indicating successful startup"
}
# send the process into the background
expect_background {
-i $someprog_spawn_id
full_buffer { }
eof {
wait -i $someprog_spawn_id
close $log_fp
}
-re {^.*\n} {
puts $log_fp $expect_out(buffer)
}
}
}
不幸的是,这个错误与消息:
can't read "log_fp": no such variable
如何在此范围内访问此变量?
答案 0 :(得分:2)
expect_background
回调脚本在全局范围内进行评估(因为该过程很可能在它们触发时完成)所以你必须将变量放在该范围内......
proc foo { } {
global log_fp
set log_fp [open "somefile" a]
# ...
或者,对于8.5,您可以使用apply
来制作绑定
expect_background "
-i \$someprog_spawn_id
full_buffer { }
[list eof [list apply {log_fp {
wait -i $someprog_spawn_id
close $log_fp
}} $log_fp]]
[list -re {^.*\n} [list apply {log_fp {
puts $log_fp $expect_out(buffer)
}} $log_fp]]
"
真的很丑陋。使用全局变量要容易得多。