mchfrnc
mchfrnc

Reputation: 5713

Expect - wait until process terminate

I am completely new in Expect, and I want to run my Python script via Telnet. This py script takes about 1 minute to execute, but when I try to run it via Telnet with Expect - it doesn't work.

I have this expect simple code:

#! /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

When I replace script.py with the one with shorter execution time - it works great. Could you tell me what should I change, so I can wait until my script.py process will terminate? Should I use timeout or sleep?

Upvotes: 0

Views: 2290

Answers (2)

Dinesh
Dinesh

Reputation: 16428

If you are sure about the execution time of the script, then you can add sleep or set the timeout to the desired value

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

Or

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

But, if the time is variant, then better handle the timeout event and wait for the prompt till some amount of time. i.e.

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"} 
}

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246764

A simpler alternative: if you don't care how long it takes to complete:

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

Upvotes: 0

Related Questions