简体   繁体   中英

calling sleep bash command in pexpect

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:

  1. 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.

  2. Change the ~ to your bash prompt to reproduce the issue.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM