Python PySerial.How to know if a port is already open?

走远了吗. 提交于 2019-12-09 17:25:44

问题


I'm trying to write an App that uses serial ports in a Linux PC, using python and PySerial. But in this PC there are other Apps using serial ports. How can I know if a port is already open by other App before trying to use it?

thanks


回答1:


Seems to be badly documented on the PySerial website, this works for me:

ser = serial.Serial(DEVICE,BAUD,timeout=1)
if(ser.isOpen() == False):
    ser.open()

A bit of a contrived example, but you get the idea. I know this question was asked a long time ago, but I had the same question today and felt anyone else finding this page would appreciate finding an answer.




回答2:


Check the return output of Serial.serial, it returns an invalid exception that can be caught

http://pyserial.sourceforge.net/pyserial_api.html http://pyserial.sourceforge.net/pyserial_api.html#serial.SerialException

Other than that, if the port is in fact closed when your program attempts to access it, the error thrown is non-fatal and is fairly clear about the reason it failed.




回答3:


This is what me helped when trying to prevent my application from failing because it was stopped and started again.

import serial

try:
  ser = serial.Serial( # set parameters, in fact use your own :-)
    port="COM4",
    baudrate=9600,
    bytesize=serial.SEVENBITS,
    parity=serial.PARITY_EVEN,
    stopbits=serial.STOPBITS_ONE
  )
  ser.isOpen() # try to open port, if possible print message and proceed with 'while True:'
  print ("port is opened!")

except IOError: # if port is already opened, close it and open it again and print message
  ser.close()
  ser.open()
  print ("port was already open, was closed and opened again!")

while True: # do something...


来源:https://stackoverflow.com/questions/6178705/python-pyserial-how-to-know-if-a-port-is-already-open

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!