Pyserial 无法像 linux shell 那样写入 tty

Pyserial cannot write to tty like the linux shell

我可以使用 linux shell 中的以下命令通过 UART 与设备通信:

echo 'CMD' > /dev/ttyPS1

我尝试使用 Pyserial 模块在 Python 中重新创建此操作,但没有任何反应。我尝试在 .py 文件和 2.7 解释器中使用它(以防出现时间延迟问题)。

import serial
ser = serial.Serial('/dev/ttyPS1', 115200)
ser.write('CMD')

有趣的是...在 运行 python 的片段之后,我无法使用 linux shell 写入设备。 stty 向我展示了 Pyserial 为设备添加了一堆选项。如果我清除这些额外的选项,那么我可以使用 linux shell 再次与我的设备通话。

在 Python 脚本之前:

>>> stty -F /dev/ttyPS1
speed 115200 baud; line = 0;
-brkint -imaxbel

在 Python 脚本之后:

>>> stty -F /dev/ttyPS1
speed 115200 baud; line = 0;
min = 0; time = 0;
-brkint -icrnl -imaxbel
-opost -onlcr
-isig -icanon -iexten -echo -echoe -echok -echoctl -echoke

为什么会发生这种行为?有没有办法让 Pyserial 像 linux shell?

如果你真的想让pyserial打开设备文件而不改变所有这些标志,或者明确地让它改变标志到他们已经拥有的值,你可以用一堆来做到这一点the constructor 的选项参数,或者在构造后设置一些属性或调用一些方法。


但是你为什么要这么做?

如果你只想做与echo等价的事情,只要做shell和echo命令所做的:将设备文件作为文件打开并写入它.

因此,其中之一:

with open('/dev/ttyPS1', 'wb') as ps1:
    ps1.write(b'CMD')

with open('/dev/ttyPS1', 'wb', buffering=0) as ps1:
    ps1.write(b'CMD')

with open('/dev/ttyPS1', 'wb') as ps1:
    ps1.raw.write(b'CMD')

ps1 = os.open('/dev/ttyPS1', os.O_WRONLY)
os.write(ps1, b'CMD')
os.close(ps1)

如果您使用 Python 2.x,则不需要 b 前缀,也没有 .raw,但其他情况类似:

with open('/dev/ttyPS1', 'wb') as ps1:
    ps1.write('CMD')

with open('/dev/ttyPS1', 'wb', 0) as ps1:
    ps1.write('CMD')

ps1 = os.open('/dev/ttyPS1', os.O_WRONLY)
os.write(ps1, 'CMD')
os.close(ps1)