[英]How to use pyserial expect on a string from serial console, then send a charater
I'm a new to python, hoping someone knows something about the issue I have. 我是python的新手,希望有人对我遇到的问题有所了解。 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.
我想捕获字符串,然后发送字符“ h”,这将中止重启。 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? 有任何想法吗?
This thread is quite old, but I hope my answer can still be useful to you. 这个线程很旧,但是我希望我的回答对您仍然有用。
The expect methods are from pexpect, not from pyserial. Expect方法来自pexpect,而不来自pyserial。 You should do something like:
您应该执行以下操作:
temp = pexpect.fdpexpect.fdspawn(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.
这包括稍后的sendline()调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.