[Python] How to reset a COM Port through python program

Discussão em 'Python' iniciado por Stack, Janeiro 31, 2025.

  1. Stack

    Stack Membro Participativo

    I am using a pymodbus library to fetch data through modbus protocol. I am using a MOXA Nport 5150 RS485 to Ethernet converter for fetching data through Real COM Mode in Windows Server 2022. For a particular COM port, the data fetching is interrupted for an unpredictable amount of time and throws PermissionError(13, 'Access is denied.') and resumes the data fetching on its own. I made many attempts to resolve this error but to no avail. The version of python I am using is 3.13.0. I even tried catching the error and restarting the python script but an error is thrown which says 'Port is not accessible'. I even tried looking up for the Port in Process Explorer but does not return any results. Can some one please help in resolving this error

    I tried the following code for restarting the python script whenever there is a permission error or serial exception:

    def restart_program():
    print(" Restarting program ")
    python = r"C:\Program Files\Python313\python.exe"
    subprocess.run([python] + sys.argv)
    sys.exit()


    I even checked whether the port is open before starting fetching of data using the below:

    port = serial.Serial(port_name,9600,timeout = 1)
    if (port.isOpen() == True):

    # data fetch code


    I even installed Windows Process Explorer to see whether any other process is using the COM port but did not find any result

    Even the COM port is not available when I tied executing the following command in CMD prompt:

    mode COM16


    I am unable to find any solution. Can some one please help.

    Continue reading...

Compartilhe esta Página