Adding a progress bar

In this how to we want to show an example on how to integrate nornir with tqdm to add a nice way of tracking progress of our script without having to print the results on screen. First, this is how the result will look like when we run the script:

../_images/demo.gif

And now the code:

  1. from nornir import InitNornir
  2. from nornir_napalm.tasks import napalm_get
  3. from tqdm import tqdm
  4. nr = InitNornir(config_file="config.yaml")
  5. def multiple_progress_bar(task, napalm_get_bar, other_bar):
  6. """
  7. This task takes two paramters that are in fact bars;
  8. napalm_get_bar and other_bar. When we want to tell
  9. to each respective bar that we are done and should update
  10. the progress we can do so with bar_name.update()
  11. """
  12. task.run(task=napalm_get, getters=["facts"])
  13. napalm_get_bar.update()
  14. tqdm.write(f"{task.host}: facts gathered")
  15. # more actions go here
  16. other_bar.update()
  17. tqdm.write(f"{task.host}: done!")
  18. # we create the first bar named napalm_get_bar
  19. with tqdm(
  20. total=len(nr.inventory.hosts), desc="gathering facts",
  21. ) as napalm_get_bar:
  22. # we create the second bar named other_bar
  23. with tqdm(
  24. total=len(nr.inventory.hosts), desc="other action ",
  25. ) as other_bar:
  26. # we call our grouped task passing both bars
  27. nr.run(
  28. task=multiple_progress_bar,
  29. napalm_get_bar=napalm_get_bar,
  30. other_bar=other_bar,
  31. )

It looks a bit daunting due to the nesting but basically we are creating two progress bars, one inside the other and then we just pass them to our grouped task. Finally, the grouped task can update the progress by calling bar_name.update(). You can also add further information using tqdm.write("more info!") if you want.