Skip to content

Commit

Permalink
added howto "Adding a progress bar to nornir" (#381)
Browse files Browse the repository at this point in the history
* added howto about how to add a progress bar to nornir

* undo change
  • Loading branch information
dbarrosop committed May 19, 2019
1 parent beeef0a commit b384439
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions docs/howto/progress_bar.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
Adding a progress bar
=====================

In this how to we want to show an example on how to integrate ``nornir`` with `tqdm <https://tqdm.github.io/>`_ 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:

.. image:: progress_bar/demo.gif

And now the code::

from nornir import InitNornir
from nornir.plugins.tasks.networking import napalm_get

from tqdm import tqdm

nr = InitNornir(config_file="config.yaml")


def multiple_progress_bar(task, napalm_get_bar, other_bar):
"""
This task takes two paramters that are in fact bars;
napalm_get_bar and other_bar. When we want to tell
to each respective bar that we are done and should update
the progress we can do so with bar_name.update()
"""
task.run(task=napalm_get, getters=["facts"])
napalm_get_bar.update()
tqdm.write(f"{task.host}: facts gathered")

# more actions go here
other_bar.update()
tqdm.write(f"{task.host}: done!")


# we create the first bar named napalm_get_bar
with tqdm(
total=len(nr.inventory.hosts), desc="gathering facts",
) as napalm_get_bar:
# we create the second bar named other_bar
with tqdm(
total=len(nr.inventory.hosts), desc="other action ",
) as other_bar:
# we call our grouped task passing both bars
nr.run(
task=multiple_progress_bar,
napalm_get_bar=napalm_get_bar,
other_bar=other_bar,
)

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.
Binary file added docs/howto/progress_bar/demo.gif
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit b384439

Please sign in to comment.