我有一个用于与微控制器通信的python程序。它会像这样打开com端口:
def STM32_connect():
ports = list(serial.tools.list_ports.comports())
for p in ports:
if "STM32" in p.description:
connection = serial.Serial(p.device, timeout = .01)
return(connection)
print("ERROR: No STM32 Device Found")
sys.exit()
serial_connection = STM32_connect()
然后做了很多事情,发送和接收数据,直到我用键盘输入关闭这个程序:
except:
print("\n Program Interrupted...")
finally:
print("\n Closing Serial Port\n")
serial_connection.close()
一切正常。我的问题是当通过断开USB电缆或关闭电路板而不正确地杀死python脚本时,我无法再连接到任何COM端口上的micro。我收到此错误:
Traceback (most recent call last):
File "/home/---/.local/lib/python3.5/site-packages/serial/serialposix.py", line 265, in open
self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
OSError: [Errno 16] Device or resource busy: '/dev/ttyACM2'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "flextester.py", line 1, in <module>
from flex_usb_class import *
File "/home/---/Code/RobotFlexTester/flex_usb_class.py", line 30, in <module>
serial_connection = STM32_connect()
File "/home/---/Code/RobotFlexTester/flex_usb_class.py", line 25, in STM32_connect
connection = serial.Serial(p.device, timeout = .01)
File "/home/---/.local/lib/python3.5/site-packages/serial/serialutil.py", line 240, in __init__
self.open()
File "/home/janey/.local/lib/python3.5/site-packages/serial/serialposix.py", line 268, in open
raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 16] could not open port /dev/ttyACM2: [Errno 16] Device or resource busy: '/dev/ttyACM2'
我可以更改COM端口,并在不同的ttyACM端口收到完全相同的错误。但是如果我尝试运行不同的python脚本,我可以连接到同一端口上的同一设备。问题似乎以某种方式被锁定到初始测试脚本,但ps -a
并未显示它仍在运行。没有我在约30秒 - 1分钟后做任何事情,问题就消失了。
答案 0 :(得分:1)
closing_wait
命令(http://manpages.ubuntu.com/manpages/zesty/man8/setserial.8.html)中查看setserial
选项(默认为30秒),当断开USB电缆连接并且连接被终止时,协议将等待closing_wait
选项中指定的时间直到它关闭端口/会话。 session_lockout
禁止将第二个进程附加到开放端口...