6

I am trying to use pexpect on serial port. I use fdpexpect as suggested. But I noticed that expect() does not obey timeout. Instead, the EOF happens.

ser = serial.Serial(sys.argv[1], 9600)
fd = fdpexpect.fdspawn(ser.fd)
fd.send('%s\r' % username)
i = fd.expect(['Password:', pexpect.TIMEOUT], timeout=30)
if i == 0:
    fd.send('%s\r' % password)
else:
    print 'Boom!'

It seems that instead of catching either, pexpect.exceptions.EOF is raised almost immediately. If I add pexpect.EOF to the list of match, EOF will be matched immediately. Granted, it is a serial port and data most likely has not arrived yet. If I add time.sleep(1) before fd.expect(), it will work. But that defeats the purpose of expect. Am I doing something wrong?

some user
  • 876
  • 1
  • 12
  • 26
  • Interesting that you mention adding the sleep helps. I have a very similar problem with getting immediate EOF (timeout ignored!!) on the first call to expect. I've found that adding and removing lines of code in my python script has either produced the problem or made it go away. I'll be trying some suggestions. – jerrylogansquare Apr 22 '20 at 01:29

1 Answers1

0

Any time you're using fdpexpect instead of plain pexpect with a spawned terminal, you have to worry about hitting the EOF of that file stream. See this answer for more information: https://stackoverflow.com/a/25770830.

I've also found that adding maxread=1 to pexpect.fdpexpect.fdspawn can help fix this, but that also slows down reading text.

Kyle Barron
  • 2,452
  • 22
  • 17