On Tuesday, November 7, 2017 at 6:06:31 AM UTC-6, Edward K. Ream wrote:

Here is another approach.  Starting from your script, it caches the 
> kernel.  The second time it is run, it successfully uses the previously 
> created kernel.
>
>     t1 = time.clock()
>     d = g.app.permanentScriptDict
>     kern = d.get('kernel')
>     print('kernel...', kern)
>     if not kern:
>         # from run_kernel, which can't be used directly
>         km = jupyter_client.KernelManager(kernel_name='python')
>         km.start_kernel()
>         kc = km.client()
>         kc.start_channels()
>         kc.wait_for_ready(timeout=60)
>         d['kernel'] = kern = kc
>

 At last I see why the result from run_kernel can't be cached.  The code is:

@contextmanager
def run_kernel(**kwargs):
    """Context manager to create a kernel in a subprocess.

    The kernel is shut down when the context exits.

    Returns
    -------
    kernel_client: connected KernelClient instance
    """
    km, kc = start_new_kernel(**kwargs)
    try:
        yield kc
    finally:
        kc.stop_channels()
        km.shutdown_kernel(now=True)

The @contextmanager decorator is part of Python's contextlib 
<https://docs.python.org/2/library/contextlib.html>module, and defines a 
factory method for use with "with" statements.

As a result, run_kernel should be used within "with" statements.  Note that 
run_kernel is not documented on the api page 
<http://jupyter-client.readthedocs.io/en/latest/api/manager.html>, so I'm 
not sure how Vitalije intuited this.

Anyway, the following code *does* work (with getIn as before), using 
jupyter_client.manager.start_new_kernel instead of run_kernel.

t1 = time.clock()
d = g.app.permanentScriptDict
kern = d.get('kernel')
if kern:
    print('existing kernel:', kern)
else:
    print('creating kernel...')
    junk, kern = jupyter_client.manager.start_new_kernel()
    d['kernel'] = kern
kern.execute(code=code, user_expressions={'a':'a'})
msg = kern.get_shell_msg()
resultDict = getIn(msg, ['content', 'user_expressions', 'a'])
result = getIn(msg, ['content', 'user_expressions', 'a', 'data', 
'text/plain'])
g.printObj(resultDict)
print('%2.4f sec' % (time.clock()-t1))

This is much better than scooping out code from run_kernel because 
start_new_kernel will be updated as necessary when new releases come out.

My next project will be to google to find out how to create objects that 
use different values of traitlets defined as class members of jupyter 
classes.

Edward

-- 
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