How to use pyserial expect on a string from serial console, then send a charater
Question: I'm a new to python, hoping someone knows something about the issue I have. I
want to control a device using serial console. A command will be sent to
reboot the device, while the device is rebooting, a string is printed. I want
to catch the string and then send a character "h" which will abort the reboot.
Code looks like this

    
    
    #! /bin/env python
    
    import serial
    import sys
    import pexpect
    from time import sleep
    from serial import SerialException
    
    ser = serial.Serial()
    ser.baudrate = 9600
    ser.port="/dev/ttyUSB0"
    ser.stopbits=serial.STOPBITS_ONE
    ser.xonxoff=0
    
    try:
        ser.open()
    except:
        sys.exit ("Error opening port")
    
    print "Serial port opened"
    ser.write('rebootnow\r')
    
    temp = ser.expect('press h now to abort reboot..')
    
    if i == 0:
        print ('Gotcha, pressing h')
        ser.sendline('h')
        print ('Reboot aborted')
    else:
        print ('Ouch, got nothing')
        time.sleep(1)
    ser.close()
    
    exit()
    

When I run the code, I get the error

    
    
    AttributeError: 'Serial' object has no attribute 'expect'
    

at line

    
    
    temp = ser.expect('press h now to abort reboot..')
    

Any ideas?


Answer: this thread is quite old, but I hope my answer can still be useful to you.

The expect methods are of pexpect, not of pyserial.

You should do something like:

    
    
    temp = pexpect.fdpexpect.fdswpan(ser)
    temp.expect("message")
    

basically, from temp onwards you should call methods on the temp object, not
on the serial object. This includes the sendline() call, later on.

