Loading screen using tqdm library

37 Views Asked by At

Good morning/evening,

I'm configuring 3 cisco switches using netmiko which is an automation python library for networking .I have the cisco configuration lines saved in the file called "IOS_config". and I have 3 switches defined in a list called "all_devices". I'm adding IOS_config configuration in each switch. I'm trying to add a loading bar using tqdm library to know how long it takes for each switch to be configured as shown below.

  with open('IOS_Image') as f:
        lines = f.read().splitlines()
    print (lines)

    all_devices = [S1, S2, S3]

    for devices in tqdm(all_devices,desc="Loading...",):
        print("configuring..." + devices['ip'] )
        net_connect = ConnectHandler(**devices)
        output = net_connect.send_config_set(lines)`
    

The issue is that tdqm has 33% step. Meaning while configuring S1, loading bar is showing 0%. When finishing S1 and going to S2, it jumps to 33% without a continuous gradual increase . I want know if there is a method with or without tqdm libray where I can see the progress while configuring each switch with a gradual increase. Thanks

1

There are 1 best solutions below

0
pyjedy On

You can iterate through each command to display a more granular progress bar. In the following example, the progress bar has 9 steps instead of 3.

from netmiko import ConnectHandler
from tqdm import tqdm

lines = [
    "errdisable recovery cause pagp-flap",
    "errdisable recovery cause dtp-flap",
    "errdisable recovery cause link-flap",
]
params = {
    "device_type": "cisco_ios",
    "username": "username",
    "password": "password",
}
S1 = {"ip": "10.0.0.1", **params}
S2 = {"ip": "10.0.0.2", **params}
S3 = {"ip": "10.0.0.3", **params}
all_devices = [S1, S2, S3]

# Calculate the total number of iterations
total_iterations = len(all_devices) * len(lines)

# Initialize tqdm bar
pbar = tqdm(
    total=total_iterations, 
    desc="Configuring Devices and Lines...", 
    position=0, 
    leave=True,
)

# Iterate through devices
for device in all_devices:
    print("Configuring..." + device["ip"])
    net_connect = ConnectHandler(**device)

    # Iterate through lines
    for line in lines:
        output = net_connect.send_config_set(line)
        # Manually update tqdm bar
        pbar.update(1)

# Close tqdm bar
pbar.close()