Skip to content

Instantly share code, notes, and snippets.

@pepijndevos
Last active July 28, 2016 06:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pepijndevos/8823394 to your computer and use it in GitHub Desktop.
Save pepijndevos/8823394 to your computer and use it in GitHub Desktop.
A Redis-based interactive Python shell.
from __future__ import print_function
import threading
import code
import sys
import contextlib
from time import sleep
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
@contextlib.contextmanager
def strstdout():
old = sys.stdout
stdout = StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
try:
input = raw_input
except NameError:
pass
class RedisConsole(code.InteractiveInterpreter):
def __init__(self, redis):
code.InteractiveInterpreter.__init__(self)
self.redis = redis
def run(self):
ps = self.redis.pubsub()
ps.subscribe("repl-input")
for input_ in ps.listen():
if input_['type'] == 'message':
with strstdout() as s:
self.runsource(input_['data'].decode())
self.redis.publish("repl-result", s.getvalue())
def results(redis):
ps = redis.pubsub()
ps.subscribe('repl-result')
for output in ps.listen():
if output['type'] == 'message':
print(output['data'].decode())
def repl(redis):
t = threading.Thread(target=results, args=(redis,))
t.daemon = True
t.start()
while True:
line = input('> ')
redis.publish('repl-input', line)
sleep(1) # give some time for data to come in
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment