How to add progress for long-hanging operations using Python
This is an upgrade story of a long-waiting program that shows nothing while progressing their success destination.
But,
It's 2020, we have now some cool packages which make our dumb operations into progress operations.
Yaspin provides a full-featured terminal spinner to show the progress during long-hanging operations.
It's easy to integrate into the existing codebase by using it as a context manager or as a function decorator.
Example
import time
from yaspin import yaspin
Using as Context Manager
with yaspin():
time.sleep(3)
Using Function decorator
@yaspin(text="Loading...")
def long_waiting():
time.sleep(3)
>> long_waiting()
Yaspin also provides an intuitive and powerful API. For example, you can easily summon a shark:
import time
from yaspin import yaspin
with yaspin().while.bold.shark.on_blue as sp:
sp.text = "Loading bar with white bold shark in blue sea"
time.sleep(5)
Features
- No external dependencies
- Runs at all major CPython versions (2.7 to 3.9)
- Support all (70+) spinners
- Easy to combine with other command-line libraries.
- Flexible API, easy to integrate
- Safe pipes and redirects
>> python script_that_uses_yaspin.py > script.log
>> python script_that_uses_yaspin.py > grep ERROR
Installation
In the environment package manager:
pip install --upgrade yaspin
Or install the latest sources from GitHub:
pip install https://github.com/pavdmyt/yaspin/archive/master.zip
Usage
Basic Example
import time
from random import randint
from yaspin import yaspin
with yaspin(text="Loading", color="yellow") as spinner:
time.sleep(2) # time consuming code
success = randint(0, 1)
if success:
spinner.ok("โ
")
else:
spinner.fail("๐ฅ ")
It is also possible to control the spinner manually:
import time
from yaspin import yaspin
spinner = yaspin()
spinner.start()
time.sleep(3) # time consuming tasks
spinner.stop()
Run any spinner you want
import time
from yaspin import yaspin, Spinner
# Compose new spinners with custom frame sequence and interval value
sp = Spinner(["๐ธ", "๐น", "๐บ", "๐ป", "๐ผ", "๐ฝ", "๐พ", "๐ฟ", "๐"], 200)
with yaspin(sp, text="Cat!"):
time.sleep(3) # cat consuming code :)
You should not write any message in the terminal using print while the spinner is open.
To write messages in the terminal without any collision with the yaspin spinner, a .write() method is provided:
# -*- coding: utf-8 -*-
import time
from yaspin import yaspin
with yaspin(text="Downloading images", color="cyan") as sp:
# task 1
time.sleep(1)
sp.write("> image 1 download complete")
# task 2
time.sleep(2)
sp.write("> image 2 download complete")
# finalize
sp.ok("โ")
Subscribe to my newsletter
Read articles from Rahul Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Rahul Singh
Rahul Singh
Was Machine Learning Developer @ Nasscom Currently Sr. Software Engineer @ HT Media