PySerial write()即时时间

2024-09-30 01:33:25 发布

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

编辑

我发现了问题所在并回答了自己的问题。

这行下面的原始问题

我在软件中实现了COM4COM5之间的串行桥(特别是HDD的免费虚拟串行配置实用程序)

我有两个不同的python脚本在Powershell的两个不同实例中启动,请先接收:

import serial
receive = serial.Serial(port = 'COM5', baudrate = 9600)
text = receive.read(100)
receive.close()
print text

然后发件人:

import serial
send = serial.Serial(port = 'COM4', baudrate = 9600, timeout = 0)
send.write("Hello")
send.close()

启动发送方脚本时,接收方脚本将获取已发送的消息(以便清楚地建立通信),但发送方脚本将立即以错误结束:

Traceback (most recent call last):
  File ".\sending.py", line 3, in <module>
    send.writelines("Hello")
  File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 270, in write
    raise writeTimeoutError
serial.serialutil.SerialTimeoutException: Write timeout

当我将发送者脚本更改为

send = serial.Serial(port = 'COM4', baudrate = 9600)

所以我的问题是:到底什么是超时?我该如何防止这种情况发生?我的意思是,数据是被发送的,所以我可能只是把整个东西放在一个try/except(and do nothing)块中,但从长远来看,这似乎是一个糟糕的解决方案。


Tags: textimport脚本sendhellocloseporttimeout
1条回答
网友
1楼 · 发布于 2024-09-30 01:33:25

线索在错误消息[1]中

File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 270, in write
raise writeTimeoutError

所以我们打开文件,找到:

if self._writeTimeout != 0: # if blocking (None) or w/ write timeout (>0)
            # Wait for the write to complete.
            #~ win32.WaitForSingleObject(self._overlappedWrite.hEvent, win32.INFINITE)
            err = win32.GetOverlappedResult(self.hComPort, self._overlappedWrite, ctypes.byref(n), True)
            if n.value != len(data):
                raise writeTimeoutError

再次阅读第一个条件:

if self._writeTimeout != 0:

所以让我们重写之前的代码

send = serial.Serial(port = 'COM4', baudrate = 9600, timeout = 0)

变成

send = serial.Serial(port = 'COM4', baudrate = 9600, writeTimeout = 0)

艾特:也不例外。

[1]设计良好的错误消息?那是新的!

相关问题 更多 >

    热门问题