Expect - 等到进程终止

Expect - wait until process terminate

我是 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 进程终止吗?我应该使用超时还是睡眠?

如果您确定脚本的执行时间,那么您可以添加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"} 
}

更简单的选择:如果您不关心完成需要多长时间:

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