Pyserial 不能很好地使用虚拟端口
问题描述
动机
我想开始学习如何使用 python 库 Pyserial.这似乎是一个非常好的图书馆,适用于很多人.我想在即将进行的项目中使用它,在该项目中我必须自动化串行通信.
I want to start leraning how to use the python library Pyserial. It seems like a really nice library that works for a lot of people. I want to use it for an upcoming project in which I have to automate serial communications.
环境
我正在运行 Ubuntu 15.04.我正在使用 Python 2.7.
I'm running Ubuntu 15.04. I'm using Python 2.7.
设置虚拟端口
我目前没有可以通过串行端口与之通信的设备.我正在使用 socat 应用程序创建两个虚拟端口,它们通过波特率9600.
I don't currently have a device that I can communicate with over a serial port. I'm using the socat application to create two virtual ports that are connected to each other with a baudrate of 9600.
$ socat -d -d pty,raw,echo=0,b9600 pty,raw,echo=0,b9600
2016/01/16 12:57:51 socat[18255] N PTY is /dev/pts/2
2016/01/16 12:57:51 socat[18255] N PTY is /dev/pts/4
2016/01/16 12:57:51 socat[18255] N starting data transfer loop with FDs [5,5] and [7,7]
$ echo "hello" > /dev/pts/2
$ cat /dev/pts/4
hello
太棒了!似乎端口可以工作!
Great! It seems like the ports work!
一个简单的pyserial脚本
我使用 pip 安装 pyserial
I install pyserial using pip
$ sudo pip install pyserial
然后我写了一点serialtest.py
Then I wrote a little serialtest.py
#!/usr/bin/env python
import serial
ser = serial.Serial('/dev/pts/2', 9600)
这就是整个serialtest.py
That is the entirety of serialtest.py
运行脚本并遇到错误
$ python serialtest.py
Traceback (most recent call last):
File "serialtest.py", line 4, in <module>
ser = serial.Serial('/dev/pts/2')
File "/home/sbl/.local/lib/python2.7/site-packages/serial/serialutil.py", line 180, in __init__
self.open()
File "/home/sbl/.local/lib/python2.7/site-packages/serial/serialposix.py", line 311, in open
self._update_dtr_state()
File "/home/sbl/.local/lib/python2.7/site-packages/serial/serialposix.py", line 605, in _update_dtr_state
fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str)
IOError: [Errno 22] Invalid argument
这是怎么回事?
调试尝试失败
这家伙说他用python 2.6成功了.我无法让 Pyserial 与 2.6 一起使用.
This guy said he had success when using python 2.6. I couldn't get Pyserial to work with 2.6.
这家伙遇到了波特率问题.我使用命令 $stty -F/dev/pts/2
仔细检查了我的波特率,并确认它实际上是 9600 的波特率.
This guy was having trouble with is baudrate. I double check my baudrate with the command $stty -F /dev/pts/2
and confirmed that it was, in fact, at a baudrate of 9600.
这家伙还声称波特率有问题并将其归因于他的内核.那是在 2012 年,所以我认为它不再相关了.
This guy also claims to have problems with baudrate and attributes it to his kernel. That was back in 2012, so I don't think it's relevant anymore.
我的问题
如何让我的 serialtest.py 脚本正常运行?
How can I get my serialtest.py script to run without error?
解决方案
为了完成这个问答,这是一个解决方案(在 Austin Philips 的链接中找到):
To make this Q&A complete, this is a solution (as found in the link by Austin Philips):
#!/usr/bin/env python
import serial
ser = serial.Serial('/dev/pts/2', 9600, rtscts=True,dsrdtr=True)
有关详细说明,请参阅此 PySerial Github 问题.
See this PySerial Github issue for more explanation.
相关文章