使用默认系统串行配置的 Pyserial

Pyserial using default system serial configuration

当使用 python pyserial 初始化串行连接时没有任何波特率,它将进入默认的 9600 波特配置

ser = serial.Serial('/dev/ttyUSB0')

这个 pyserial 是否有任何选项可以使用通过另一个应用程序或 stty linux 命令配置的已配置设置读取/写入串行端口?

我研究了 pySerial 的源代码。这似乎是不可能的。 PySerial 有一组默认值。如果我没记错的话,当你调用 open() 方法时,它总是将端口配置为这些默认值或你将它们更改为的任何设置。

这是 Serial::open() 方法实现的相关部分:

def open(self):
    """\
    Open port with current settings. This may throw a SerialException
    if the port cannot be opened."""

    # ... ...

    # open
    try:
        self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
    except OSError as msg:
        self.fd = None
        raise SerialException(msg.errno, "could not open port %s: %s" % (self._port, msg))
    #~ fcntl.fcntl(self.fd, fcntl.F_SETFL, 0)  # set blocking

    try:
        # **this is where configuration occurs**
        self._reconfigure_port(force_update=True)
    except:
        try:
            os.close(self.fd)
        except:
            # ignore any exception when closing the port
            # also to keep original exception that happened when setting up
            pass
        self.fd = None
        raise
    else:

https://github.com/pyserial/pyserial/blob/master/serial/serialposix.py#L299

我看到两个适合你的选择;在调用 Serial::open() 之前从系统获取您感兴趣的设置(可能使用 stty)并显式设置这些设置。

另一种选择是subclassPySerial的Serialclass,重新实现::open()方法,跳过配置部分:

    # self._reconfigure_port(force_update=True)

不过我不确定这是否可行。这可能会导致问题,因为实现的其他部分期望端口处于特定配置中,但事实并非如此。

更新:我认为 open() 方法的更好实现是从打开的端口读取设置并设置 Serial 对象的必要 attributes/properties 以反映这些设置。