| 1 |
"""An internal ipykernel example.""" |
| 2 |
# ----------------------------------------------------------------------------- |
| 3 |
# Imports |
| 4 |
# ----------------------------------------------------------------------------- |
| 5 |
|
| 6 |
import sys |
| 7 |
|
| 8 |
from IPython.lib.kernel import connect_qtconsole |
| 9 |
|
| 10 |
from ipykernel.kernelapp import IPKernelApp |
| 11 |
|
| 12 |
|
| 13 |
# ----------------------------------------------------------------------------- |
| 14 |
# Functions and classes |
| 15 |
# ----------------------------------------------------------------------------- |
| 16 |
def mpl_kernel(gui): |
| 17 |
"""Launch and return an IPython kernel with matplotlib support for the desired gui""" |
| 18 |
kernel = IPKernelApp.instance() |
| 19 |
kernel.initialize( |
| 20 |
[ |
| 21 |
"python", |
| 22 |
"--matplotlib=%s" % gui, |
| 23 |
#'--log-level=10' |
| 24 |
] |
| 25 |
) |
| 26 |
return kernel |
| 27 |
|
| 28 |
|
| 29 |
class InternalIPKernel: |
| 30 |
"""An internal ipykernel class.""" |
| 31 |
|
| 32 |
def init_ipkernel(self, backend): |
| 33 |
"""Start IPython kernel with GUI event loop and mpl support.""" |
| 34 |
self.ipkernel = mpl_kernel(backend) |
| 35 |
# To create and track active qt consoles |
| 36 |
self.consoles = [] |
| 37 |
|
| 38 |
# This application will also act on the shell user namespace |
| 39 |
self.namespace = self.ipkernel.shell.user_ns |
| 40 |
|
| 41 |
# Example: a variable that will be seen by the user in the shell, and |
| 42 |
# that the GUI modifies (the 'Counter++' button increments it): |
| 43 |
self.namespace["app_counter"] = 0 |
| 44 |
# self.namespace['ipkernel'] = self.ipkernel # dbg |
| 45 |
|
| 46 |
def print_namespace(self, evt=None): |
| 47 |
"""Print the namespace.""" |
| 48 |
print("\n***Variables in User namespace***") |
| 49 |
for k, v in self.namespace.items(): |
| 50 |
if not k.startswith("_"): |
| 51 |
print(f"{k} -> {v!r}") |
| 52 |
sys.stdout.flush() |
| 53 |
|
| 54 |
def new_qt_console(self, evt=None): |
| 55 |
"""start a new qtconsole connected to our kernel""" |
| 56 |
return connect_qtconsole(self.ipkernel.abs_connection_file, profile=self.ipkernel.profile) |
| 57 |
|
| 58 |
def count(self, evt=None): |
| 59 |
"""Get the app counter value.""" |
| 60 |
self.namespace["app_counter"] += 1 |
| 61 |
|
| 62 |
def cleanup_consoles(self, evt=None): |
| 63 |
"""Clean up the consoles.""" |
| 64 |
for c in self.consoles: |
| 65 |
c.kill() |