Skip to content

Instantly share code, notes, and snippets.

@felixbd
Created September 17, 2023 17:42
Show Gist options
  • Save felixbd/81634516368e29a742d9873a35e66058 to your computer and use it in GitHub Desktop.
Save felixbd/81634516368e29a742d9873a35e66058 to your computer and use it in GitHub Desktop.
pytime
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
pytime.py - Display current time or countdown as ASCII art in the terminal
"""
# add to .zshrc
# alias pytime="$HOME/pytime.py"
import os
import time
import curses
import argparse
import sys
import pyfiglet
def sec2str(sec: int, hide_sec: bool = False) -> str:
return f"{sec // 3600 :02d}:{sec // 60 :02d}:{sec % 60 :02d}."[:-4 if hide_sec else -1]
def count_up(hide_sec: bool = False) -> int:
temp: int = 0
while True:
yield f"+ {sec2str(temp, hide_sec)}"
time.sleep(1) # FIXME ...
temp += 1
def count_down(sec: int, hide_sec: bool = False) -> str:
try:
for i in range(sec, 0, -1):
yield f"- {sec2str(i, hide_sec)}"
time.sleep(1) # FIXME ...
yield from count_up(hide_sec)
except KeyboardInterrupt as err:
return
def current_time(hide_sec: bool = False) -> str:
try:
while True:
yield time.strftime(f"%H:%M{''if hide_sec else ':%S'}")
time.sleep(1) # ist ok ...
except KeyboardInterrupt as err:
return
def shell_print(stdscr, text):
stdscr.clear()
font = pyfiglet.Figlet(font="future") # banner, future, emboss, emboss2, big, smblock, pagga, smbraille, letter
ascii_art = font.renderText(text)
stdscr.addstr(0, 0, ascii_art)
stdscr.refresh()
def main(stdscr):
parser = argparse.ArgumentParser(description="Display current time as ASCII art")
parser.add_argument("-f", "--font", default="block", help="Font to use for ASCII art")
parser.add_argument("-c", "--countdown", type=int, default=0, help="Number of sec to count down")
parser.add_argument("-hsec", "--hide-sec", action="store_true", help="Hiding seconds")
args = parser.parse_args()
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
stdscr.bkgd(' ', curses.color_pair(1))
curses.curs_set(0)
if args.countdown > 0:
for s in count_down(args.countdown, args.hide_sec):
shell_print(stdscr, s)
for t in current_time(args.hide_sec):
shell_print(stdscr, t)
if __name__ == "__main__":
try:
curses.wrapper(main)
except KeyboardInterrupt as err:
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment