Python:如何读取COM端口上的()直到指定字符串?

2024-05-17 02:54:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个Python程序,用于使用AT命令自动设置调制解调器(不需要知道这是什么)

我使用串口模块进行串口通信。你知道吗

它的工作方式是我发送一个命令,然后我想“保存”响应,直到最后出现一个表示“OK”的字符串。我试过这个:

import serial
ser = serial.Serial(port='COM15', baudrate=115200, timeout=3, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE)
intline =''
ser.write('AT+COPS?'+'\r\n')    '''This specific commands asks for network status'''
while ser.inWaiting() >0:
    intline += ser.read(1)
if 'Greentel' in intline:
    print "Internet access"
else:
    print "No internet access"

我的问题是,有时我得到多个线路响应。例如,对于这里使用的命令,我得到的响应是:

"+UMWI: 0,4

+UMWI: 0,5

AT+COPS?

+COPS: 0,0,"Greentel",7

OK"

我真正想要的是做一个函数,我可以调用它来读取它,直到它符合OK,把文本放在一个字符串/列表中,让我在其中搜索特定的单词。你知道吗


Tags: 模块字符串命令程序调制解调器accessserialok
1条回答
网友
1楼 · 发布于 2024-05-17 02:54:56

我想我会发布我的解决方案,因为其他人在Python中使用AT命令的可能性很小。 我所做的是让一个函数读取输入并将其存储在字符串中,直到遇到所选的停止符。我是这样做的:

def read2sign(command, stopSign):
ser.flushInput()
temp = ''
ser.write(command +'\r\n')
while stopSign not in temp:
    temp += ser.read(1)
    print " -"     '''For debugging purpose'''
    print temp
print temp
return temp

我也有点想说抱歉过早发布。我想我得再多试试:-)

相关问题 更多 >