pySerial - 有没有办法一次选择多个端口? [英] pySerial - Is there a way to select on multiple ports at once?

查看:40
本文介绍了pySerial - 有没有办法一次选择多个端口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发需要与许多串行端口通信的应用程序.我还没有找到一种方法来做到这一点,而无需为每个端口使用线程.有没有办法用单线程来做到这一点?比如一次在多个端口上选择或轮询?我正在使用 pyserial 2.6

I am developing app that need to communicate with many serial ports. I havnt found a way to do this without using thread per port. Is there a way to do this with single thread?something like select or poll on multiple ports at once? I am using pyserial 2.6

推荐答案

我假设您在类似 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.

这篇关于pySerial - 有没有办法一次选择多个端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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