Here is example script that I have made so far.
import jupyter_client
import pprint
code = '''import math
a = math.sin(1)'''
def getIn(r, pth):
    for p in pth:
        r = r.get(p, {})
    return r
def getMessagesUntilIdle(kern):
    resp = []
    while True:
        msg = kern.get_iopub_msg()
        estate = getIn(msg, ['content', 'execution_state'])
        resp.append(msg)
        if estate == 'idle':
            break
    return resp

with jupyter_client.run_kernel(kernel_name='python3') as kern:
    kern.execute(code=code, user_expressions={'a':'a'})
    # after executing given code, kernel replies with the message
    # containing the expressions we have asked (i.e. 'a')
    msg = kern.get_shell_msg()
    # each expression we asked for is returned as a dict
    resultDict = getIn(msg, ['content', 'user_expressions', 'a'])
    # result as plain text
    result = getIn(msg, ['content', 'user_expressions', 'a', 'data', 
'text/plain'])
    g.es('---------code--------')
    g.es(code)
    g.es('---result:', result)
    g.es(pprint.pformat(resultDict))


It doesn't do too much. It calculates sin(1).
Function jupyter_client.run_kernel returns a blocking version of jupyter 
client enclosed in a context. That means that the methods get_shell_msg, 
and others get_..._msg will block until the message arrives. This 
simplifies the example but for real use, we should use non-blocking client 
and read messages on iopub channel which inform us when kernel has started 
to execute our code (it becomes busy), and when it becomes idle again, we 
can read the result message from the shell channel. 

Instead of using every time another kernel enclosed in a python context 
which will expire when the context is left, perhaps kernel client can be 
created directly using jupyter_client.KernelClient(**kwargs) and instance 
stored in c.user_dict. It is non-blocking client.

HTH Vitalije

-- 
You received this message because you are subscribed to the Google Groups 
"leo-editor" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/leo-editor.
For more options, visit https://groups.google.com/d/optout.

Reply via email to