Python:写入和读取串行端口 [英] Python: Writing to and Reading from serial port

查看:59
本文介绍了Python:写入和读取串行端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了文档,但似乎无法找到直接的答案.我有一个连接到计算机的调制解调器使用的所有 COM 端口的列表.从这个列表中,我尝试打开它,向它发送一个命令,如果它有任何回复,则将其添加到另一个列表中.我不完全确定我是否正确使用了 pyserial 的读写功能.

I've read the documentation, but can't seem to find a straight answer on this. I have a list of all COM Ports in use by Modems connected to the computer. From this list, I try to open it, send it a command, and if it says anything back, add it to another list. I'm not entirely sure I'm using pyserial's read and write functions properly.

i=0
for modem in PortList:
    for port in modem:
        try:
            ser = serial.Serial(port, 9600, timeout=1)
            ser.close()
            ser.open()
            ser.write("ati")
            time.sleep(3)
            print ser.read(64)
            if ser.read(64) is not '':
                print port
        except serial.SerialException:
            continue
        i+=1

我没有从 ser.read() 中得到任何信息.我总是得到空字符串.

I'm not getting anything out of ser.read(). I'm always getting blank strings.

推荐答案

ser.read(64) 应该是 ser.read(size=64);ser.read 使用关键字参数,而不是位置参数.

ser.read(64) should be ser.read(size=64); ser.read uses keyword arguments, not positional.

此外,您正在从端口读取两次;您可能想要做的是:

Also, you're reading from the port twice; what you probably want to do is this:

i=0
for modem in PortList:
    for port in modem:
        try:
            ser = serial.Serial(port, 9600, timeout=1)
            ser.close()
            ser.open()
            ser.write("ati")
            time.sleep(3)
            read_val = ser.read(size=64)
            print read_val
            if read_val is not '':
                print port
        except serial.SerialException:
            continue
        i+=1

这篇关于Python:写入和读取串行端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆