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

前端 未结 3 1169
面向向阳花
面向向阳花 2021-02-20 12:54

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

3条回答
  •  一向
    一向 (楼主)
    2021-02-20 13:35

    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...
    

提交回复
热议问题