【问题标题】:Timeout value with pyserial is not working on Windowspyserial 的超时值在 Windows 上不起作用
【发布时间】:2012-12-23 13:40:33
【问题描述】:

我在 64 位 Windows 7 机器上运行 Python 2.7.3,它已连接(通过 USB->RS232 电缆)到运行相同 Python 版本 (2.7.3) 的 64 位 Ubuntu 机器。

我遇到了一个问题,timeout=None 在 Windows 7 端似乎无法正常工作,我不知道为什么。

这是我在 Win 方面的内容:

>>> import serial
>>> s = serial.Serial(3)
>>> s.baudrate = 9600
>>> s
Serial<id=0x203a320, open=True>(port='COM4', baudrate=9600, bytesize=8, parity='N',
stopbits=1, timeout=None, xonxoff=False, rtscts=False, dsrdtr=False)
>>> s.read(5)
''                  <--- returns right away
>>> s.timeout = 0
>>> s.read(5)
''                  <--- correctly returns right away
>>> s.timeout = 10
>>> s.read(5)       <--- correctly waits 10s

现在我已经阅读了文档 here 并且我知道如果我不给它超时 None 它应该永远等待,并且 0 超时它应该立即返回,但 None 是默认值它没有等待......我想知道是否发生了变化,但是当我在 Linux 端尝试代码时,它可以工作:

>>> import serial
>>> s = serial.Serial("/dev/ttyUSB0")
>>> s.baudrate = 9600
>>> s
Serial<id=0x7f325e002b50, open=True>(port='/dev/ttyUSB0', baudrate=9600, bytesize=8, 
parity='N', stopbits=1, timeout=None, xonxoff=False, rtscts=False, dsrdtr=False)
>>> s.read(5)
''                  <--- correctly waits forever
>>> s.timeout = 0
>>> s.read(5)
''                  <--- correctly returns right away
>>> s.timeout = 10
>>> s.read(5)       <--- correctly waits 10s

在 Windows 上进行设置时是否有任何已知的注意事项?有谁知道为什么我会看到这个问题?关于其他我可以尝试帮助诊断此故障的任何想法?

【问题讨论】:

    标签: python windows timeout pyserial


    【解决方案1】:

    我在 Raspberry Pi 上遇到了同样的问题。值得注意的是 USB-RS232 电缆!这似乎与纯 RS232 接口有不同的行为。当您从端口读取 n 字节时,即使没有可用数据,它也将始终返回 n“0”字节。特别是它会用前面提到的“0”字节填充一个请求超过 in_waiting 承诺的读取请求。解决这个问题的唯一方法是使用 in_waiting 并仅读取属性承诺的字节数。

    【讨论】:

      【解决方案2】:

      在带有 python 2.7.3 和 pyserial 2.6 的 windows 7 x64 上运行良好:

      >>> import serial
      >>> s = serial.Serial(1)
      >>> Serial<id=0x3ea5518, open=True>(port='COM2', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=False, rtscts=False, dsrdtr=False)
      >>> s.read(5)
      # ... after receiving real data ... 
      '\xb99\xad\x87\xc2'
      

      您使用什么版本的 PySerial? 我已经从 Christoph Gohlke1 的 Unofficial Windows Binaries for Python Extension Packages 中编译了二进制文件。 也许你应该试试这个。

      【讨论】:

        猜你喜欢
        • 2016-08-21
        • 1970-01-01
        • 2018-07-25
        • 2017-02-26
        • 2017-04-26
        • 2016-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多