Skip to content

Instantly share code, notes, and snippets.

@bagrow
Created February 14, 2011 08:46
Show Gist options
  • Save bagrow/825625 to your computer and use it in GitHub Desktop.
Save bagrow/825625 to your computer and use it in GitHub Desktop.
example pause/unpause/quit python script
#!/usr/bin/python
import sys, os, time
import tty
from select import select
class TerminalFile:
"""Adapted from http://code.activestate.com/recipes/203830/"""
def __init__(self,infile):
if not infile.isatty():
raise Exception()
self.file = infile
# prepare for getch:
self.save_attr=tty.tcgetattr(self.file)
newattr=self.save_attr[:]
newattr[3] &= ~tty.ECHO & ~tty.ICANON
tty.tcsetattr(self.file, tty.TCSANOW, newattr)
def __del__(self):
# restoring stdin:
import tty # required this import here
tty.tcsetattr(self.file, tty.TCSADRAIN, self.save_attr)
def getch(self):
if select([self.file],[],[],0)[0]:
return self.file.read(1)
return ""
if __name__=="__main__":
print "Press p to pause/unpause and q to quit..."
s = TerminalFile( sys.stdin )
paused = False
i = 0
while True:
char = s.getch()
if char == 'q':
sys.stdout.write("\n")
sys.exit(0)
elif char == 'p':
paused = (not paused)
if not paused:
sys.stdout.write("\r%06d" % i)
sys.stdout.flush()
i += 1
time.sleep(0.01)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment