Skip to content

Instantly share code, notes, and snippets.

@timtadh
Created January 12, 2011 16:38
Show Gist options
  • Save timtadh/776418 to your computer and use it in GitHub Desktop.
Save timtadh/776418 to your computer and use it in GitHub Desktop.
python repl howto
left = chr(27)+chr(91)+chr(68)
right = chr(27)+chr(91)+chr(67)
backspace = left + ' ' + left
def clear_line(prompt, l):
for x in xrange(150 - l):
sys.stdout.write(right)
for x in xrange(150):
sys.stdout.write(backspace)
sys.stdout.write(prompt)
sys.stdout.flush()
if ord(x) == 127: #backspace
if prompt == list(): continue
promptpos -= 1
del prompt[promptpos]
elif ord(x) == 27: #leading character
os.read(fd, 1) #don't need to look at this character
z = os.read(fd, 1)
if ord(z) == 65: #up
sys.stdout.write(chr(27)+chr(91)+chr(66))
if history: prompt = list(history[histpos])
if histpos == -1: histpos = len(history) - 1
histpos -= 1
promptpos = len(prompt)
elif ord(z) == 66: #down
#sys.stdout.write(chr(27)+chr(91)+chr(65))
histpos = -1
prompt = list()
promptpos = 0
elif ord(z) == 67: #right
if promptpos < len(prompt): promptpos += 1
else: sys.stdout.write(left)
elif ord(z) == 68: #left
if promptpos > 0: promptpos -= 1
else: sys.stdout.write(right)
else:
if x == '\n': break
prompt.insert(promptpos, x)
promptpos += 1
history = list()
histpos = -1
exit = False
while not exit:
try:
prompt = READ LOGIC
except KeyboardInterrupt:
print 'exiting'
exit = True
break
exit = EVAL_LOGIC(prompt)
sys.stdout.write(chr(27)+chr(91)+chr(68))
sys.stdout.flush()
sys.stdout.write('> ')
sys.stdout.flush()
prompt = list()
promptpos = 0
while 1:
try:
x = os.read(fd, 1)
except KeyboardInterrupt:
sys.stdout.write('exiting\n')
sys.stdout.flush()
exit = True
break
if [control key]
[some logic for control keys]
else:
if x == '\n': break
prompt.insert(promptpos, x)
promptpos += 1
clear_line('> ', len(prompt))
sys.stdout.write(''.join(prompt))
sys.stdout.flush()
for x in xrange(len(prompt) - promptpos):
sys.stdout.write(left)
sys.stdout.flush()
prompt = ''.join(prompt)
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] = new[3] & ~ termios.ICANON
new[3] = new[3] & ~ termios.ECHOCTL
termios.tcsetattr(fd, termios.TCSADRAIN, new)
try:
# your repl logic here
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment