Created
July 6, 2012 19:42
-
-
Save strangemonad/3062342 to your computer and use it in GitHub Desktop.
iPython-reflector - Remote python execution via an iPython kernel
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
#! /usr/bin/env python | |
import sys | |
import time | |
from IPython.lib.kernel import find_connection_file | |
from IPython.zmq.blockingkernelmanager import BlockingKernelManager | |
def is_idle(sub_message, last_idle): | |
if sub_message['msg_type'] != 'status': | |
return last_idle | |
return sub_message['content']['execution_state'] == 'idle' | |
def pyout_result(sub_message, last_pyout): | |
if sub_message['msg_type'] != 'pyout': | |
return last_pyout | |
return sub_message['content']['data'] | |
# Config / startup | |
km = BlockingKernelManager() | |
try: | |
cf = find_connection_file('maru') | |
km.connection_file = cf | |
km.load_connection_file() | |
except: | |
print "No running iPython kernel run `ipython console -f maru`" | |
km.start_channels() | |
# Run stuff | |
code = sys.stdin.read() | |
shell = km.shell_channel | |
km.shell_channel.execute(code) | |
# Get_msg is blocking, we call it once assuming the | |
# next message wil always be the response to the execute | |
# we just sent off. | |
# | |
# Some assumptions: | |
# - We're the only client connecting to this kernel | |
# - We aren't creating other activity that would lead | |
# to other messages | |
# | |
# Yes, there is a non-blocking mode but what happens | |
# if the computation we sent over is long running? | |
# XXX process response for errors so we don't loop | |
# XXX TODO probably some kind of event machine here | |
# reply = shell.get_msg() | |
# print reply | |
# More assumptions | |
# The pub channel sees: | |
# status -> busy | |
# pyin (replay of the command we just sent) | |
# stuff (possibly pyouts) | |
# ... | |
# status -> idle | |
idle, result = False, None | |
while not idle: | |
time.sleep(0.5) | |
for message in km.sub_channel.get_msgs(): | |
# grab latest idle edge trigger | |
idle = is_idle(message, idle) | |
# grab last pyout (overrite old ones) | |
result = pyout_result(message, result) | |
# For now only return plain text MIM type results | |
print result['text/plain'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I tried to run this Program. But getting error in from IPython.zmq.blockingkernelmanager import BlockingKernelManager. Though IPython.zmq is installed.
Error - No module named 'IPython.zmq'