Skip to content

Instantly share code, notes, and snippets.

@nhamilakis
Created August 30, 2022 12:19
Show Gist options
  • Save nhamilakis/37ff05fceb1c6dea398de57cfbb2449b to your computer and use it in GitHub Desktop.
Save nhamilakis/37ff05fceb1c6dea398de57cfbb2449b to your computer and use it in GitHub Desktop.
Diplay a rich.console.status with a self updating "Time Elapsed" information on the side
from datetime import datetime
import contextlib
from time import sleep
from threading import Thread
from rich.console import Console
# pip install humanize
import humanize
@contextlib.contextmanager
def timed_status(status: str, complete_status:str, spinner="aesthetic"):
""" Self time keeping rich.status """
stop_threads = False
console = Console()
def status_updater():
start = datetime.now()
def timed_label(txt):
diff = humanize.precisedelta(start - datetime.now(), minimum_unit="seconds", format="%d")
return f"{txt} (Elapsed Time: {diff})"
with console.status(timed_label(status), spinner=spinner) as st:
while True:
sleep(1)
st.update(timed_label(status))
if stop_threads:
break
console.print(timed_label(complete_status))
worker = Thread(target=status_updater)
worker.daemon = True
worker.start()
yield None
stop_threads = True
worker.join()
if __name__ == '__main__':
with timed_status(status="Working...", complete_status="Work done."):
cpt = 0
while True:
sleep(1)
cpt += 1
if cpt >= 100:
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment