【问题标题】:Progress bar in Netmiko's send_config_set()Netmiko 的 send_config_set() 中的进度条
【发布时间】:2021-08-03 07:36:03
【问题描述】:

我想在 send_config_set(rendered_template,cmd_verify=False) 上的 Python 脚本中添加进度条。 该 render_template 是动态生成的,因此它的大小可能会有所不同。的命令也可以更改。 如何添加进度条以便我可以显示send_config_set() 命令的进度。 以下是我尝试过的代码

animation = "|/-\\"            
for i in range(nlines):
    device_handler.send_config_set(rendered_template,cmd_verify=False)
    time.sleep(0.1)
    sys.stdout.write("\r" + animation[i % len(animation)])
    sys.stdout.flush()
print ("End!")

它首先执行命令而不显示进度条,当命令执行时它显示进度条。

寻求帮助!!

谢谢!

【问题讨论】:

    标签: python automation progress-bar cisco netmiko


    【解决方案1】:

    我认为你应该在循环结束后发送sys.stdout.write("]\n") 来结束刷新。

    animation = "|/-\\"            
    for i in range(nlines):
        device_handler.send_config_set(rendered_template,cmd_verify=False)
        time.sleep(0.1)
        sys.stdout.write("\r" + animation[i % len(animation)])
        sys.stdout.flush()
    sys.stdout.write("]\n")  # this ends the progress bar
    print ("End!")
    

    这个answer 应该非常适合您的情况。

    代码中的进度条并不是真正的进度条,因为命令是通过send_config_set() 发送的,应该先完成,然后执行sys.stdout.write("\r" + animation[i % len(animation)])。此外,使用send_config_set 会多次发送命令(基于nlines 值),因为它在“for 循环” 中!您可以使用send_commandsend_command_timing一一发送命令。

    请查看tqdm,这是一个非常有用的 Python 可扩展进度条库。

    使用tqdm 非常简单。使用 tqdm 和 Netmiko 的完整演示:

    from netmiko import ConnectHandler
    from tqdm import tqdm
    
    device = {
        "device_type": "cisco_ios",
        "ip": "",
        "username": "",
        "password": "",
        "session_log": "whatever.log",
    }
    
    rendered_template = ["show ip interface brief", "show running-config", "show inventory"]
    nlines = len(rendered_template)
    
    with ConnectHandler(**device) as net_connect:
        for i in tqdm(range(nlines), unit="command", desc="show commands"):
            output = net_connect.send_command_timing(rendered_template[i], cmd_verify=False)
    print("Done!")
    

    如果不需要返回 output,则使用列表推导式。

    with ConnectHandler(**device) as net_connect:
        # List comprehension
        [
            net_connect.send_command_timing(rendered_template[i], cmd_verify=False)
            for i in tqdm(range(nlines), unit="command", desc="show commands")
        ]
    

    输出

    show commands: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:12<00:00,  4.26s/command]
    Done!
    

    【讨论】:

    • 这正是我的代码所缺少的! =)