且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

pySerial - 有没有办法一次选择多个端口?

更新时间:2021-11-20 22:49:36

我假设您在类似 unix 的平台上使用 PySerial...

I'm assuming you are using PySerial on a unix like platform...

由于 PySerial 对象实现了 fileno() 以获取底层文件您可以将它们直接传递给 select 这将允许您一次处理多个 PySerial 对象.

Since PySerial objects implement fileno() to get the underlying file descriptor you can pass them straight into select which will allow you to do deal with multiple PySerial objects at once.

另一种选择是设置 nonblocking() 并处理您的读取和写入可能会返回 errno.EWOULDBLOCK 错误这一事实.这可能是最简单的方法了.

Another alternative would be to set nonblocking() and deal with the fact that your reads and writes may return errno.EWOULDBLOCK errors. This is probably the simplest method.

第三种选择是使用双绞串口如果你不把你的脑袋转过来做事情的方式.

A third alternative would be to use twisted serial ports if you don't ming getting your head round the way twisted does things.

更新

对于 Windows,除了使用线程之外,几乎唯一的选择是使用 inWaiting() 方法.定期轮询您的所有串行端口,从中读取 inWaiting().如果有内容在等待,那么您可以读取该内容并且仅读取那么多字节而不会阻塞.

For Windows, pretty much your only alternative other than using threads is to use the inWaiting() method. Poll all your serial ports regularly reading inWaiting() from them. If there is stuff waiting then you can read that and only that many bytes without blocking.

不幸的是,pyserial 没有输出缓冲区中有多少可用空间"方法,这意味着当您写入串行端口时,您有阻塞的风险.如果您正在实施典型的串行端口协议,那么几千字节的默认缓冲区大小将确保这通常不会成为问题.

Unfortunately pyserial doesn't have a "how much free space is there in the output buffer" method which means that when you write to serial ports you are at risk of blocking. If you are implementing a typical serial port protocol the default buffer sizes of a few kilobytes will ensure that this isn't normally a problem.