import sys
import os
import time
import termios
import tty
import fcntl
import errno
KEY = "u"
def read_characters(f):
fd = f.fileno()
# put descriptor in non-blocking mode
flags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
try:
while 1:
try:
yield f.read(1)
except IOError as e:
if e.errno == errno.EAGAIN:
# no more characters to read
# right now
break
finally:
# restore blocking mode
fcntl.fcntl(fd, fcntl.F_SETFL, flags)
def main():
fd = sys.stdin.fileno()
# save current termios settings
old_settings = termios.tcgetattr(fd)
# tty sets raw mode using termios module
tty.setraw(fd)
try:
while True:
time.sleep(1)
for c in read_characters(sys.stdin):
if c == KEY: break
else:
c = None
if c == KEY: break
sys.stdout.write("still going\r\n")
finally:
# restore terminal settings
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
if __name__ == "__main__":
main()