Created
May 29, 2013 05:51
-
-
Save ekimekim/5668217 to your computer and use it in GitHub Desktop.
A gevent-based script that copies input to output, but interrupts every second to paint the current time at the top of the screen.
May change the time format with an optional argument.
This file contains 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
""" | |
A gevent-based script that copies input to output, but interrupts every second to paint the current time at the top of the screen. | |
May change the time format with an optional argument. | |
Time format is as per the date(1) command, as well as the following escapes: | |
\e -> ESC character | |
\t -> Tab | |
\\ -> Literal \ | |
For example, you could color your time output bold blue with the argument '\e[1;34m%X\e[m' | |
""" | |
import sys, os | |
from time import strftime | |
from time import sleep | |
from signal import signal, SIGALRM, setitimer, ITIMER_REAL | |
from errno import EINTR | |
format_escapes = { | |
r'\e': '\x1b', | |
r'\t': '\t', | |
r'\n': '\x1b[B\x1b[G', | |
r'\\': '\\' | |
} | |
def main(progname, _time_format='%X'): | |
global time_format | |
time_format = replace_all(_time_format, format_escapes) | |
signal(SIGALRM, on_alarm) | |
setitimer(ITIMER_REAL, 1, 1) | |
patrick() | |
def on_alarm(signum, frame): | |
s = "\x1b[s\x1b[H\x1b[2K" + strftime(time_format) + "\x1b[B\x1b[2K\x1b[u" | |
while s: | |
n = os.write(sys.stdout.fileno(), s) | |
s = s[n:] | |
def patrick(): | |
c = None | |
while 1: | |
try: | |
n = 0 | |
c = sys.stdin.read(1) if not c else c | |
if not c: | |
break | |
n = os.write(sys.stdout.fileno(), c) | |
except (OSError, IOError), ex: | |
if ex.errno != EINTR: | |
raise | |
if n: c = None | |
def replace_all(s, replacements): | |
for item in replacements.items(): | |
s = s.replace(*item) | |
return s | |
if __name__=='__main__': | |
sys.exit(main(*sys.argv)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment