Skip to content

Instantly share code, notes, and snippets.

@jayendra13
Created October 4, 2018 06:32
Show Gist options
  • Save jayendra13/b9e1fb438b86e68a21fafeca9d8c505c to your computer and use it in GitHub Desktop.
Save jayendra13/b9e1fb438b86e68a21fafeca9d8c505c to your computer and use it in GitHub Desktop.
from zmq.eventloop import ioloop
ioloop.install()
from zmq.eventloop.ioloop import ZMQIOLoop
from zmq.eventloop.zmqstream import ZMQStream
from functools import partial
from jupyter_client import MultiKernelManager
from tornado import gen
from tornado.concurrent import Future
from pprint import pprint
km = MultiKernelManager()
reply_futures = {}
def reply_callback(session, stream, msg_list):
print("{}".format(type(stream.io_loop)))
idents, msg_parts = session.feed_identities(msg_list)
reply = session.deserialize(msg_parts)
parent_id = reply['parent_header'].get('msg_id')
reply_future = reply_futures.get(parent_id)
pprint(reply)
print('\n')
if reply_future:
if "execute_reply" == reply["msg_type"]:
reply_future.set_result(reply)
def setup_kernel():
kernel_id = km.start_kernel('matlab')
kernel_client = km.get_kernel(kernel_id).client()
kernel_client.start_channels()
shell_stream = ZMQStream(kernel_client.shell_channel.socket)
iopub_stream = ZMQStream(kernel_client.iopub_channel.socket)
shell_stream.on_recv_stream(partial(reply_callback, kernel_client.session))
iopub_stream.on_recv_stream(partial(reply_callback, kernel_client.session))
return kernel_client
@gen.coroutine
def execute(kernel_client, code):
print("Is kernel alive: {}".format(kernel_client.is_alive()))
msg_id = kernel_client.execute(code)
f = reply_futures[msg_id] = Future()
print(msg_id)
yield f
raise gen.Return(msg_id)
def main(code_):
kernel_client = setup_kernel()
if kernel_client:
loop = ioloop.IOLoop.current()
r = loop.run_sync(lambda: execute(kernel_client, code_))
print 'returned from ioloop {}'.format(r)
if __name__ == '__main__':
code_ = "magic(6"
main(code_)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment