我想在ubuntu 20.04中以pyserial独占方式打开串口设备。我尝试了以下两种方法。
1.在pyserial中使用exclusive标志。
ser = Serial(port=serialdevice, baudrate=115200, bytesize=8, timeout=2, exclusive=True)
1.使用fcntl如下。
try:
ser = Serial(port=serialdevice, baudrate=115200, bytesize=8, timeout=2)
if ser.isOpen():
try:
fcntl.flock(ser.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except Exception as e:
print(e)
except Exception a e:
print(e)
这两种方法都行不通。在/var/lock下没有生成任何锁文件。
最后,我只能在/var/lock下手动创建锁文件,如下所示。
try:
device_name = serialdevice.split("/")[2]
lock_file_name = "/var/lock/LCK.."+device_name
ser = Serial(port=serialdevice, baudrate=115200, bytesize=8, timeout=2)
if ser.isOpen():
open(lock_file_name, 'w').write(str(os.getpid()))
else:
print("port not open")
except Exception as e:
print("Failed to open serial port exclusively. Pls check if the serial port is already used by other tools")
print(e)
return
我可以问一下前两种方法有什么问题吗?打开串口一般用手动方法吗?当python脚本退出时,我需要手动删除锁文件吗?
谢谢你,谢谢
1条答案
按热度按时间8yparm6h1#
1.在pyserial中使用exclusive标志。
使用
exclusive=True
创建Serial对象将导致pyserial在内部使用flock来锁定串行设备,正如我们在serialposix.py的源代码中看到的那样。1.使用fcntl如下。
这与第一种方法是一样的。
在/var/lock下没有生成任何锁文件。
上面的方法锁定了串行字符设备文件,因此您不会看到在/var/lock下生成的文件,因为锁定文件实际上是
/dev/ttyXXX
文件本身。最后一种方法将不起作用,您只创建了一个名为
"/var/lock/LCK.."+device_name
的文件,但不会发生锁定。如果您想使用您的最终方法来使用一个单独的锁文件,您仍然需要自己对"/var/lock/LCK.."+device_name
文件进行分组。范例:你真的不需要删除文件,因为它几乎不占用任何空间,但它是很好的清理。