Last active
July 28, 2016 06:51
-
-
Save pepijndevos/8823394 to your computer and use it in GitHub Desktop.
A Redis-based interactive Python shell.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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