期待 - 等到流程终止

时间:2015-04-27 12:36:35

标签: telnet expect

我在Expect中是全新的,我想通过Telnet运行我的Python脚本。 这个py脚本大约需要1分钟才能执行,但是当我尝试使用Expect通过Telnet运行它时 - 它不起作用。

我希望这简单的代码:

#! /usr/bin/expect
spawn telnet <ip_addr>
expect "login"
send "login\r"
expect "assword"
send "password\r"
expect "C:\\Users\\user>\r"
send "python script.py\r"
expect "C:\\Users\\user>\r"
close

当我将script.py替换为执行时间较短的脚本时,效果很好。你能告诉我我应该改变什么,所以我可以等到我的script.py进程终止?我应该使用超时还是睡眠?

2 个答案:

答案 0 :(得分:1)

如果您确定脚本的执行时间,则可以添加sleep或将timeout设置为所需的值

send "python script.py\r"
sleep 60; # Sleeping for 1 min
expect "C:\\Users\\user>"; # Now expecting for the prompt

set timeout 60;
send "python script.py\r"
expect "C:\\Users\\user>"; # Now expecting for the prompt

但是,如果时间是变体,那么更好地处理timeout事件并等待提示直到一段时间。即

set timeout 60; # Setting timeout as 1 min;
set counter 0
send "python script.py\r"
expect {
    # Check if 'counter' is equal to 5
    # This means, we have waited 5 mins already.
    # So,exiting the program.
    if {$counter==5} {
        puts "Might be some problem with python script"
        exit 1
    }
    # Increase the 'counter' in case of 'timeout' and continue with 'expect'
    timeout { 
        incr counter;
        puts "Waiting for the completion of script..."; 
        exp_continue; # Causes the 'expect' to run again
    }
    # Now expecting for the prompt
    "C:\\Users\\user>" {puts "Script execution is completed"} 
}

答案 1 :(得分:0)

更简单的替代方案:如果您不在乎完成所需的时间:

set timeout -1
# rest of your code here ...