[IPython-dev] How to preconfigure notebook environment in v1.1?

Adam Sadovsky asadovsky at gmail.com
Wed Oct 30 23:28:19 EDT 2013


I recently upgraded from IPython 0.13 to 1.1.
In 0.13, I was able to execute code in each notebook at startup, but the
kernel code has changed and I can't figure out how to do it anymore. Could
someone point me in the right direction?

Here's my code that worked in 0.13:
import os
import textwrap

from IPython.frontend.html.notebook.notebookapp import NotebookApp
from IPython.zmq.blockingkernelmanager import BlockingKernelManager
from IPython.zmq.entry_point import base_launch_kernel

class CustomKernelManager(BlockingKernelManager):
  """Runs custom code in each notebook when it starts."""

  def start_kernel(self, *args, **kwargs):
    kernel = super(CustomKernelManager, self).start_kernel(*args, **kwargs)

    # Initialize the communication channels and run custom code.
    prepare_notebook = textwrap.dedent("""\
      %pylab inline
      from custom.module.path import foo
    return kernel

  def start_channels(self, *args, **kwargs):
    """Checks if the channels are running before starting them."""
    # IPython will try to start the channels after launching the kernel,
    # without checking if they had already been started, which will cause
    # a double initialization problem.
    # This problem exists because IPython does not expect start_channels to
    # invoked by start_kernel, which is something that our custom
    # does.
    # Adding this check solves the issue.
    if not self.channels_running:
      super(CustomKernelManager, self).start_channels(*args, **kwargs)

notebookapp = NotebookApp.instance()
notebookapp.config_file_name = os.environ['HOME'] + '/.my_notebookrc'
notebookapp.kernel_manager.kernel_manager_factory = CustomKernelManager


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ipython-dev/attachments/20131030/62fe4770/attachment.html>

More information about the IPython-dev mailing list