Skip to content

Instantly share code, notes, and snippets.

@jayendra13
Created January 16, 2017 05:49
Show Gist options
  • Save jayendra13/76a4f5726428882013ea62d94974da5c to your computer and use it in GitHub Desktop.
Save jayendra13/76a4f5726428882013ea62d94974da5c to your computer and use it in GitHub Desktop.
from zmq.eventloop import ioloop
ioloop.install()
from zmq.eventloop.zmqstream import ZMQStream
from functools import partial
from tornado import gen
from tornado.concurrent import Future
from jupyter_client import BlockingKernelClient
from pprint import pprint
import logging, os, zmq
reply_futures = {}
context = zmq.Context()
publisher = context.socket(zmq.PUSH)
publisher.connect("tcp://127.0.0.1:5253")
def reply_callback(session, stream, msg_list):
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)
print("{} \n".format(reply))
if reply_future:
if "execute_reply" == reply["msg_type"]:
reply_future.set_result(reply)
publisher.send(reply)
def fv_execute():
code = 'print ("hello")'
msg_id = execute(code)
return msg_id
def get_connection_file(kernel_id):
json_file = 'kernel-{}.json'.format(kernel_id)
return os.path.join('/tmp',json_file)
def execute(code,):
kernel_id = '46459cb4-fa34-497a-8e3d-dfb3ab4476fd'
cf = get_connection_file(kernel_id)
kernel_client = BlockingKernelClient(connection_file=cf)
#loop = ioloop.IOLoop.instance()
loop = ioloop.IOLoop.current()
setup_listener(kernel_client, loop)
loop.start()
msg_id = loop.run_sync(lambda: execute_(kernel_client,code))
return msg_id
def setup_listener(kernel_client, io_loop):
shell_stream = ZMQStream(kernel_client.shell_channel.socket, io_loop=io_loop)
iopub_stream = ZMQStream(kernel_client.iopub_channel.socket, io_loop=io_loop)
shell_stream.on_recv_stream(partial(reply_callback, kernel_client.session))
iopub_stream.on_recv_stream(partial(reply_callback, kernel_client.session))
print("{} {}".format(shell_stream.io_loop, iopub_stream.io_loop))
@gen.coroutine
def execute_(kernel_client, code):
msg_id = kernel_client.execute(code)
f = reply_futures[msg_id] = Future()
print("Is kernel alive: {}".format(kernel_client.is_alive()))
print(msg_id)
yield f
raise gen.Return(msg_id)
if __name__ == '__main__':
fv_execute()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment