gpt4 book ai didi

tcl - 如何在expect脚本中清理之前的expect_buf

转载 作者:行者123 更新时间:2023-12-04 13:50:01 25 4
gpt4 key购买 nike

我写了一个期望函数来获取命令的输出,我的代码如下

proc do_cmd {cmd id} {
set spawn_id $id
send "$cmd\r"
expect "$cmd\r"
expect {
-re "\n(.*)\r\n" {return $expect_out(1,string)}
default {exit 1}
}
}

如果我只调用一次函数,它会工作正常并返回我想要的东西,但如果我不停地调用它,它会返回不需要的东西。
# test case 1
set ret [do_cmd $mycmd $spawn_id]
puts "$mycmd returns $ret" # the return value is ok

# test case 2
set ret [do_cmd $mycmd $spawn_id]
set ret [do_cmd $mycmd $spawn_id]
puts "$mycmd returns $ret" # the return value is not something I want

我使用'exp_internal 1'来调试它,发现第二个调用命令中的expect_out仍然保存着之前的输出信息并导致了匹配的问题,那么我该如何清理expect_out缓冲区(我试图将其设置为空字符串但它不起作用,)或者我还能做些什么来避免这个问题?提前致谢。

最佳答案

Don Libes 对您的方案的建议如下,

Sometimes it is even useful to say:

expect *

Here the * matches anything. This is like saying, "I don't care what's in the input buffer. Throw it away." This pattern always matches, even if nothing is there. Remember that * matches anything, and the empty string is anything! As a corollary of this behavior, this command always returns immediately. It never waits for new data to arrive. It does not have to since it matches everything.



引用: Exploring Expect

在这种情况下,在您所需的匹配之后,最好尝试将匹配保存到某个变量,然后简单地添加代码 expect *最后。这将清空缓冲区。您的代码可以更改如下。
proc do_cmd {cmd id} {
set spawn_id $id
send "$cmd\r"
#Looks like you are looking for a particular command to arrive
expect "$cmd\r"
#Then you have one more expect here which is you want to get it
expect {
#Saving the value sub match to the variable 'result'
-re "\n(.*)\r\n" {set result $expect_out(1,string)}}
}
#Causing the buffer to clear and it will return quickly
expect *
return $result
}

除此之外,还有一种方法可以取消设置 expect_out(buffer)内容本身将从 expect_out 中删除“缓冲区”索引可以表示为的数组
unset expect_out(buffer)

当下一场比赛发生时, expect_out数组将更新索引“缓冲区”,我们可以获得新的 expect_out(buffer)值(value)。更换 expect *如果您更喜欢使用这种方式,请使用上面的代码。

这是获得我们真正想要的东西的一种解决方法。您可以继续使用任何方法。选择权在你。 :)

关于tcl - 如何在expect脚本中清理之前的expect_buf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25523356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com