Last active
March 25, 2025 10:25
-
-
Save ay0ks/58b162726bce95303d56be2cd6341331 to your computer and use it in GitHub Desktop.
Loading spinner in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
with Loading(): | |
# some heavy calculations |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment