Skip to content

Instantly share code, notes, and snippets.

@thomasballinger
Created August 3, 2014 20:43
Show Gist options
  • Select an option

  • Save thomasballinger/eb871b3fb99747b62b3b to your computer and use it in GitHub Desktop.

Select an option

Save thomasballinger/eb871b3fb99747b62b3b to your computer and use it in GitHub Desktop.
import code
import re
import select
import signal
import socket
import sys
from curtsies import input
from curtsies.fmtfuncs import green, blue
from subprocess import Popen, PIPE
# #python irc seems to think subprocess is the only way to go. I'm going
# to look into the latency of rpc again.
# This would totally make virtualenv support easier!
def process():
input_gen = input.Input()
p = Popen(['python', __file__, 'kernel'], stdin=PIPE, stdout=PIPE)
line = ''
with input.Input() as input_gen:
while True:
rs, ws, es = select.select([p.stdout, input_gen], [], [])
for r in rs:
if r is p.stdout:
output = r.readline()
if re.match('[<][<].*[>][>]\n', output):
vars = eval(output[len('<<locals: "'):-len('">>\n')])
cw = line.rsplit(None, 1)[-1] if line else ''
completions = [v for v in vars if v.startswith(cw)]
print
print ' '.join(str(blue(comp)) for comp in completions)
print line,
sys.stdout.flush()
else:
print green(output),
elif r is input_gen:
e = input_gen.send(0)
if e is None:
continue
elif e == u"<TAB>":
p.stdin.write('<<locals>>\n')
else:
if e == u"<SPACE>":
line += ' '
elif e == u"<BACKSPACE>":
line = line[:-1]
elif e in (u"<Ctrl-j>",):
p.stdin.write(line+'\n')
line = ''
else:
line += e
p.stdin.write('<<locals>>\n')
print
print line,
sys.stdout.flush()
def main_kernel():
interp = code.InteractiveInterpreter()
def dispatch(msg):
if re.match('<<locals>>', msg):
sys.stdout.write('<<locals: %r>>\n' % repr(list(interp.locals.keys())+list(__builtins__.__dict__.keys())))
sys.stdout.flush()
else:
interp.runsource(msg)
sys.stdout.flush()
def run():
while True:
msg = raw_input()
sys.stderr.flush()
dispatch(msg)
run()
def main():
process()
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == 'kernel':
main_kernel()
else:
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment