Reputation: 2115
I am tryig to call sleep 10
command in pexpect
sendline. However, pexpect is not waiting for sleep to finish.
Following is the Example which can be used to reproduce the issue.
import pexpect
import sys
child = pexpect.spawn('bash', encoding='utf-8')
child.logfile = sys.stdout
child.expect('~')
child.sendline("date");
child.expect('2020')
child.sendline('sleep 10')
child.expect('~',timeout=12)
child.sendline('date')
Note:
I am already aware of using time.sleep()
function , however there is a restriction(bash commands and expected output is sent to the python code from some different tool) in my requirements which make be to use sleep from bash only. This example is just a scaled down version of the issue.
Change the ~
to your bash prompt to reproduce the issue.
Upvotes: 1
Views: 297
Reputation: 12255
The problem is that your child.expect('~',timeout=12)
is returning immediately, because there already is an old ~
in the buffer that can match.
When you send date
, you would have had a line such as
Tue Jun 9 15:32:45 GMT 2020
~ $
You then expected 2020
, which leaves \r\n~ $
still in the buffer.
You should either always use a match that goes right up to the prompt for the next command, or flush the buffer before sending a new command. Though there is a .flush()
method it does not do this. You can instead use, say,
child.read_nonblocking(size=9999, timeout=.1)
Upvotes: 1