Python pySerial等待#&引用;用于打印USB串行设备输出的字符
我正在编写一个连接到USB串行设备的python脚本。无论何时发送并执行命令,PIC都会返回一个hashtag。Ie.“命令执行成功。\n#” 我希望我的python脚本在输出数据之前等待hashtag。我该怎么做? 这是我的。它似乎没有实际打印从图片接收到的文本。谢谢你的帮助Python pySerial等待#&引用;用于打印USB串行设备输出的字符,python,python-2.7,pyserial,Python,Python 2.7,Pyserial,我正在编写一个连接到USB串行设备的python脚本。无论何时发送并执行命令,PIC都会返回一个hashtag。Ie.“命令执行成功。\n#” 我希望我的python脚本在输出数据之前等待hashtag。我该怎么做? 这是我的。它似乎没有实际打印从图片接收到的文本。谢谢你的帮助 if port.isOpen(): try: for x in range(0,100): time.sleep(0.05) port.wr
if port.isOpen():
try:
for x in range(0,100):
time.sleep(0.05)
port.write("command 1" + "\r\n")
numLines = 0
// wait for "#" to print output
while True:
response = port.readline()
if "#" in response:
print(response)
numLines = numLines + 1
if(numLines >= 1):
break
time.sleep(0.05)
port.write("command 2" + "\r\n")
numLines = 0
// wait for "#" to print output
while True:
response = port.readline()
if "#" in response:
print(response)
numLines = numLines + 1
if(numLines >= 1):
break
time.sleep(0.05)
port.write("command 3" + "\r\n")
numLines = 0
// wait for "#" to print output
while True:
response = port.readline()
if "#" in response:
print(response)
numLines = numLines + 1
if(numLines >= 1):
break
except Exception, e1:
print("An error occured: " + str(e1))
port.close()
port.readline()
将读取串行端口,直到它接收到\n
。因此,响应将包含字符串“Command executed successfully.\n”。由于此字符串中没有“#”,因此代码将再次遇到port.readline()
语句。这次它将读取“#”,但由于没有“\n”,代码将被卡在那里,导致无限循环
Pyserial提供了一个名为read():
读取(大小=1)
参数:size–要读取的字节数。返回:从中读取的字节数
港口。返回类型:字节从串行端口读取大小字节。如果
如果设置了超时,则可能会根据请求返回较少的字符。没有
超时它将阻塞,直到读取请求的字节数
read()提供一个参数大小(默认值为1),用于指定要读取的字节数。因此,您可以指定PIC发送的字符串中的字节数作为参数。您还可以使用以下备选方案:
// wait for "#" to print output
while True:
response += port.read()
if "#" in response:
print(response)
numLines = numLines + 1
if(numLines >= 1):
break
port.readline()
将读取串行端口,直到它接收到\n
。因此,响应将包含字符串“Command executed successfully.\n”。由于此字符串中没有“#”,因此代码将再次遇到port.readline()
语句。这次它将读取“#”,但由于没有“\n”,代码将被卡在那里,导致无限循环
Pyserial提供了一个名为read():
读取(大小=1)
参数:size–要读取的字节数。返回:从中读取的字节数
港口。返回类型:字节从串行端口读取大小字节。如果
如果设置了超时,则可能会根据请求返回较少的字符。没有
超时它将阻塞,直到读取请求的字节数
read()提供一个参数大小(默认值为1),用于指定要读取的字节数。因此,您可以指定PIC发送的字符串中的字节数作为参数。您还可以使用以下备选方案:
// wait for "#" to print output
while True:
response += port.read()
if "#" in response:
print(response)
numLines = numLines + 1
if(numLines >= 1):
break
如果您向设备发送一些空白,就像它是一个终端命令一样,它将在响应中插入您的“#”。我已经成功地使用了这种方法。具体地说,我发送一个空格“”加上终端行结尾(即“\n”或“\r\n”,具体取决于设备) 如果您向设备发送一些空白,就像它是一个终端命令一样,它会将它插入一个带有“#”的响应中。我已经成功地使用了这种方法。具体地说,我发送一个空格“”加上终端行结尾(即“\n”或“\r\n”,具体取决于设备)
response+=port.read()。更好的方法是:target='#';response=(response+port.read())[-len(target):]
如果目标==response
,response+=port.read(),[-len(target):]
如果“#”到达得很晚,则累积的字符串可能会变得非常大。更好的方法是:target='#';response=(response+port.read())[-len(target):]
使累积的字符串不再是目标字符串,无论大小,如果target==response,则后跟。