Skip to content

Instantly share code, notes, and snippets.

@ay0ks
Last active March 25, 2025 10:25
Show Gist options
  • Save ay0ks/58b162726bce95303d56be2cd6341331 to your computer and use it in GitHub Desktop.
Save ay0ks/58b162726bce95303d56be2cd6341331 to your computer and use it in GitHub Desktop.
Loading spinner in python
import sys
import time
from itertools import cycle
from multiprocessing import Process
class UnixLoading:
def __enter__(self):
def thread(self):
for char in itertools.cycle("|/-\\"):
sys.stdout.write(f"{char} Loading\r")
sys.stdout.flush()
time.sleep(0.29)
self.thread = multiprocessing.Process(
target = thread,
args = (self,),
daemon = True
)
self.started = int(str(time.clock_gettime_ns(0))[0:13])
self.thread.start()
def __exit__(self, _type, value, traceback):
self.thread.terminate()
self.ended = int(str(time.clock_gettime_ns(0))[0:13])
if _type is not None:
sys.stdout.write("❌ Error after %s seconds.\n\r" % \
abs((self.started - self.ended) / 1000)
)
sys.stdout.flush()
else:
sys.stdout.write("✅ Success. (lasted %s seconds.)\n\r" % \
abs((self.started - self.ended) / 1000)
)
sys.stdout.flush()
return None
with Loading():
# some heavy calculations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment