我认为你应该在循环结束后发送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_command或send_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!