我想在 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!")
它首先执行命令而不显示进度条,当命令执行时它会显示进度条。
寻求帮助!!
谢谢!
我认为你应该在循环结束后发送
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!")
这个答案应该完全适合您的情况。
代码中的进度条并不是真正的进度条,因为命令是通过send_config_set()
发送的,应该先完成,然后执行
sys.stdout.write("\r" + animation[i % len(animation)])
。此外,使用
send_config_set
会多次发送命令(基于
nlines
值),因为它位于 “for 循环” 内!您可以使用
send_command
或
send_command_timing
逐一发送命令。请检查使用
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!
2023 年 8 月 17 日更新netmiko==4.2.0 和 tqdm==4.66.1
rendered_template = ["show ip interface brief", "show running-config", "show inventory"]
with ConnectHandler(**device) as net_connect:
for command in tqdm(iterable=rendered_template, unit="command", desc="show commands"):
output = net_connect.send_command(command, cmd_verify=False, read_timeout=60)
print("Done!")
show commands: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [01:10<00:00, 3.53s/command