DEV Community

Cover image for Python CMD Progress Bars
Corentin-zrt
Corentin-zrt

Posted on

Python CMD Progress Bars

Python is one of the most used programming language in the world. Today we're going to create a progress bar in the CMD console.

Package installation

First of all, you just need to import, by pip, the package rich. In your CMD, write this :

pip install rich
Enter fullscreen mode Exit fullscreen mode

And then the package will be installed on your computer.

The script

After that, you can create a script with the name you want, follow by the .py extension. And paste this in it :

import time
from rich.progress import Progress

with Progress() as progress:

    task1 = progress.add_task("[red]Downloading...", total=100)
    task2 = progress.add_task("[green]Processing...", total=100)
    task3 = progress.add_task("[cyan]Cooking...", total=100)

    while not progress.finished:
        progress.update(task1, advance=0.5)
        progress.update(task2, advance=0.3)
        progress.update(task3, advance=0.9)
        time.sleep(0.02)
Enter fullscreen mode Exit fullscreen mode

Nevermind, I'll explain what it does.

The first line just imports the time module. The second line imports the module rich and especially the class Progress. The 'with' keyword means that we asign the class Progress() to the variable progress in the block below.
The first three variables are tasks as it's written and there are two arguments to pass :

  1. The name : it's a string value to describe what the progress bar does. We see [ ] with colors : it's just to have a colored text on the screen.
  2. total : it's the value that the progress bar goes to. In the exemple, it goes from 0 to 100.

Now there is a while loop and this will run until all the progess bars asigned before will be finished. Below this while, we have three instructions that increase task bars by a certain value each time (with the advance parameter).

And then we stop the script during 0.02 seconds.

In the console, you should have something like this :

Image description

Conclusion

Just like this, you have created a simple progress bar using the rich package in python. Don't forget to look at the documentation of rich at this link : https://rich.readthedocs.io/en/stable/

See you in the next topic. Bye Bye coder friends... 👨‍💻

Top comments (3)

Collapse
 
adamkatora profile image
Adam Katora

Beautiful, I was thinking of writing some CLI tools in bash to automate some simple tasks, but leaning more towards python for more cross platform support.

This is definitely pushing me more towards doing it in python since this makes adding progress bars look very straightforward

Collapse
 
yewyaw profile image
CubicO

Super nice thing, thanks for this post. And thanks for bring my attention to rich lib:)

Collapse
 
corentinzrt profile image
Corentin-zrt

Nice to you ;)