1

我想在我的 Python 脚本中的send_config_set(rendered_template,cmd_verify=False)上添加一个进度条。该 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!")

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

寻求帮助!!

谢谢!

4

1 回答 1

2

I think you should end flushing by sending sys.stdout.write("]\n") after the loop ends.

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!")

This answer should perfectly fit your case.

The progressbar in your code is not really a progressbar, because commands are sent through send_config_set() which should be completed first, then the sys.stdout.write("\r" + animation[i % len(animation)]) is executed. Also, using send_config_set sends the commands multiple times (based on the nlines value) because it's within a "for loop"! You can send commands one by one using send_command or send_command_timing.

Please check tqdm, it's an extensible progressbar library for Python that would be very useful.

Using tqdm is pretty straightforward. A complete demo using tqdm with 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!")

or use a list comprehension if output is not necessary to be returned.

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")
    ]

Output

show commands: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:12<00:00,  4.26s/command]
Done!
于 2021-08-03T13:03:41.933 回答