Retrying Iteration of a Loop if it gets failed

In this post I am going to explain a code block which I used for retrying iteration of a loop if it gets failed.

This is the code

def get_port_list_traffic(port_list, connnection_handler):
    port_traffic_data_list = []
    # variables for adding total traffic
    total_in_traffic = 0
    total_out_traffic = 0
    for port in port_list:
        retries = 0
        max_retries = 5
        while retries < max_retries:
            try:
                d = get_port_traffic_data(port,timestamp,connection_handler)
                port_traffic_data_list.append(d)
                # cumulative sum of traffic from each ports
                total_in_traffic = total_in_traffic + d['in_traffic']
                total_out_traffic = total_out_traffic + d['out_traffic']
            except Exception as e:
                retries = retries + 1
                if hasattr(e,'message'):
                    print(e.message)
                else:
                    print(e)
                print(f"Retrying {port['id']} {retries}th time")
            else:
                retries = 0
                break

This code snippet is part of code which gets port statistics from a network device. I have more than 30 ports in the device. The code scans every port and gets the statistics. Then repeats the process after a certain period of time for eg 30 minutes.
But the code randomly gets errors without any clear reason when scanning the ports.

links

social