Pyserial using default system serial configuration
When initializing serial connection using python pyserial without any baud-rate, It goes to the default 9600 baud configuration
ser = serial.Serial('/dev/ttyUSB0')
Does this pyserial have any option that it read / write to the serial port with the already configured settings that which configured through another application or stty linux command ?
I've investigated pySerial's source code. It seems this is not possible. PySerial has a set of defaults. And if I'm not mistaken, when you call open()
method it will always configure port to these defaults or whatever setting you changed them to.
This is the relevant bit from the implementation of Serial::open()
method:
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
I see two alternatives for you; get the settings that you are interested from the system (using stty
maybe) before calling Serial::open()
and set these settings explicitly.
Another option is to subclass PySerial's Serial
class, re implement ::open()
method, skip the configuration part:
# self._reconfigure_port(force_update=True)
I'm not sure if that would work though. It may cause problems, because other parts of the implementation are expecting port to be in a specific configuration, but it isn't.
UPDATE: I think a better implementation of open()
method would read the settings from the opened port and set necessary attributes/properties of the Serial
object to reflect these settings.
上一篇: 更改MAC终端上的波特率stty
下一篇: Pyserial使用默认的系统串行配置