##// END OF EJS Templates
Merge pull request #7339 from minrk/spec.display_name...
Merge pull request #7339 from minrk/spec.display_name update new notebook button with kernelspec changes

File last commit:

r18933:5b6c286c
r19746:a4d26578 merge
Show More
consoleapp.py
345 lines | 13.0 KiB | text/x-python | PythonLexer
Paul Ivanov
refactoring common code out of qtconsole
r5603 """ A minimal application base mixin for all ZMQ based IPython frontends.
This is not a complete console app, as subprocess will not be able to receive
input, there is no real readline support, among other limitations. This is a
Fernando Perez
Fix all remaining imports that used `IPython.frontend`.
r11024 refactoring of what used to be the IPython/qt/console/qtconsoleapp.py
Paul Ivanov
refactoring common code out of qtconsole
r5603 """
Paul Ivanov
remove load_connection_file from consoleapp...
r16497 # Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
Paul Ivanov
refactoring common code out of qtconsole
r5603
MinRK
improve cleanup of connection files...
r5609 import atexit
Paul Ivanov
refactoring common code out of qtconsole
r5603 import os
import signal
import sys
import uuid
from IPython.config.application import boolean_flag
from IPython.core.profiledir import ProfileDir
MinRK
update terminal console to new KM / KC APIs
r10287 from IPython.kernel.blocking import BlockingKernelClient
MinRK
update imports with new layout
r10284 from IPython.kernel import KernelManager
MinRK
move utils.kernel (formerly entry_point and lib.kernel) to kernel.util
r9353 from IPython.kernel import tunnel_to_kernel, find_connection_file, swallow_argv
Thomas Kluyver
Nicer error message when kernel is not found
r16383 from IPython.kernel.kernelspec import NoSuchKernel
Paul Ivanov
refactoring common code out of qtconsole
r5603 from IPython.utils.path import filefind
from IPython.utils.traitlets import (
Paul Ivanov
more DRYing out of consoleapp
r16504 Dict, List, Unicode, CUnicode, CBool, Any
Paul Ivanov
refactoring common code out of qtconsole
r5603 )
MinRK
mv IPython.zmq to IPython.kernel.zmq
r9372 from IPython.kernel.zmq.kernelapp import (
MinRK
move IPKernelApp from zmq.ipkernel to zmq.kernelapp...
r9357 kernel_flags,
kernel_aliases,
Paul Ivanov
refactoring common code out of qtconsole
r5603 IPKernelApp
)
MinRK
define InlineBackend configurable in its own file...
r13167 from IPython.kernel.zmq.pylab.config import InlineBackend
MinRK
mv IPython.zmq to IPython.kernel.zmq
r9372 from IPython.kernel.zmq.session import Session, default_secure
from IPython.kernel.zmq.zmqshell import ZMQInteractiveShell
MinRK
fix `--existing` with non-localhost IP...
r12110 from IPython.kernel.connect import ConnectionFileMixin
Paul Ivanov
refactoring common code out of qtconsole
r5603
MinRK
avoid executing code in utils.localinterfaces at import time...
r12591 from IPython.utils.localinterfaces import localhost
Paul Ivanov
refactoring common code out of qtconsole
r5603
#-----------------------------------------------------------------------------
# Aliases and Flags
#-----------------------------------------------------------------------------
MinRK
move IPKernelApp from zmq.ipkernel to zmq.kernelapp...
r9357 flags = dict(kernel_flags)
Paul Ivanov
zmqterminal now uses the zmq mixin app
r5604
# the flags that are specific to the frontend
# these must be scrubbed before being passed to the kernel,
# or it will raise an error on unrecognized flags
Paul Ivanov
refactoring common code out of qtconsole
r5603 app_flags = {
MinRK
rename IPythonMixinConsoleApp to IPythonConsoleApp...
r5618 'existing' : ({'IPythonConsoleApp' : {'existing' : 'kernel*.json'}},
Paul Ivanov
refactoring common code out of qtconsole
r5603 "Connect to an existing kernel. If no argument specified, guess most recent"),
}
app_flags.update(boolean_flag(
MinRK
rename IPythonMixinConsoleApp to IPythonConsoleApp...
r5618 'confirm-exit', 'IPythonConsoleApp.confirm_exit',
Paul Ivanov
refactoring common code out of qtconsole
r5603 """Set to display confirmation dialog on exit. You can always use 'exit' or 'quit',
to force a direct exit without any confirmation.
""",
"""Don't prompt the user when exiting. This will terminate the kernel
if it is owned by the frontend, and leave it alive if it is external.
"""
))
flags.update(app_flags)
MinRK
move IPKernelApp from zmq.ipkernel to zmq.kernelapp...
r9357 aliases = dict(kernel_aliases)
Paul Ivanov
refactoring common code out of qtconsole
r5603
Paul Ivanov
zmqterminal now uses the zmq mixin app
r5604 # also scrub aliases from the frontend
Paul Ivanov
refactoring common code out of qtconsole
r5603 app_aliases = dict(
MinRK
fix `--existing` with non-localhost IP...
r12110 ip = 'IPythonConsoleApp.ip',
transport = 'IPythonConsoleApp.transport',
MinRK
rename IPythonMixinConsoleApp to IPythonConsoleApp...
r5618 hb = 'IPythonConsoleApp.hb_port',
shell = 'IPythonConsoleApp.shell_port',
iopub = 'IPythonConsoleApp.iopub_port',
stdin = 'IPythonConsoleApp.stdin_port',
existing = 'IPythonConsoleApp.existing',
f = 'IPythonConsoleApp.connection_file',
Paul Ivanov
refactoring common code out of qtconsole
r5603
Thomas Kluyver
Expose --kernel arg for selecting kernel on console and qtconsole
r16272 kernel = 'IPythonConsoleApp.kernel_name',
Paul Ivanov
refactoring common code out of qtconsole
r5603
MinRK
rename IPythonMixinConsoleApp to IPythonConsoleApp...
r5618 ssh = 'IPythonConsoleApp.sshserver',
Paul Ivanov
refactoring common code out of qtconsole
r5603 )
aliases.update(app_aliases)
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
MinRK
only include kernel config in `--help` output...
r17960 classes = [KernelManager, ProfileDir, Session]
Paul Ivanov
refactoring common code out of qtconsole
r5603
MinRK
fix `--existing` with non-localhost IP...
r12110 class IPythonConsoleApp(ConnectionFileMixin):
Paul Ivanov
refactoring common code out of qtconsole
r5603 name = 'ipython-console-mixin'
description = """
The IPython Mixin Console.
This class contains the common portions of console client (QtConsole,
ZMQ-based terminal console, etc). It is not a full console, in that
launched terminal subprocesses will not be able to accept input.
The Console using this mixing supports various extra features beyond
the single-process Terminal IPython shell, such as connecting to
existing kernel, via:
ipython <appname> --existing
as well as tunnel via SSH
"""
MinRK
add InlineBackend to ConsoleApp class list...
r7291 classes = classes
Paul Ivanov
refactoring common code out of qtconsole
r5603 flags = Dict(flags)
aliases = Dict(aliases)
MinRK
update terminal console to new KM / KC APIs
r10287 kernel_manager_class = KernelManager
kernel_client_class = BlockingKernelClient
Paul Ivanov
refactoring common code out of qtconsole
r5603
kernel_argv = List(Unicode)
MinRK
Split swallow_argv into standalone function in lib.kernel...
r5620 # frontend flags&aliases to be stripped when building kernel_argv
frontend_flags = Any(app_flags)
frontend_aliases = Any(app_aliases)
Paul Ivanov
refactoring common code out of qtconsole
r5603
# create requested profiles by default, if they don't exist:
auto_create = CBool(True)
# connection info:
MinRK
enable IPC transport for kernels...
r7321
Paul Ivanov
refactoring common code out of qtconsole
r5603 sshserver = Unicode('', config=True,
help="""The SSH server to use to connect to the kernel.""")
sshkey = Unicode('', config=True,
help="""Path to the ssh key to use for logging in to the ssh server.""")
def _connection_file_default(self):
return 'kernel-%i.json' % os.getpid()
existing = CUnicode('', config=True,
help="""Connect to an already running kernel""")
Thomas Kluyver
Special cased kernel name is 'python', not 'native'
r16333 kernel_name = Unicode('python', config=True,
Thomas Kluyver
Expose --kernel arg for selecting kernel on console and qtconsole
r16272 help="""The name of the default kernel to start.""")
Paul Ivanov
refactoring common code out of qtconsole
r5603 confirm_exit = CBool(True, config=True,
help="""
Set to display confirmation dialog on exit. You can always use 'exit' or 'quit',
to force a direct exit without any confirmation.""",
)
MinRK
only include kernel config in `--help` output...
r17960
@property
def help_classes(self):
"""ConsoleApps can configure kernels on the command-line
But this shouldn't be written to a file
"""
return self.classes + [IPKernelApp] + IPKernelApp.classes
MinRK
Split swallow_argv into standalone function in lib.kernel...
r5620 def build_kernel_argv(self, argv=None):
"""build argv to be passed to kernel subprocess"""
Paul Ivanov
refactoring common code out of qtconsole
r5603 if argv is None:
argv = sys.argv[1:]
MinRK
Split swallow_argv into standalone function in lib.kernel...
r5620 self.kernel_argv = swallow_argv(argv, self.frontend_aliases, self.frontend_flags)
Paul Ivanov
refactoring common code out of qtconsole
r5603
def init_connection_file(self):
"""find the connection file, and load the info if found.
The current working directory and the current profile's security
directory will be searched for the file if it is not given by
absolute path.
When attempting to connect to an existing kernel and the `--existing`
argument does not match an existing file, it will be interpreted as a
fileglob, and the matching file in the current profile's security dir
with the latest access time will be used.
MinRK
improve cleanup of connection files...
r5609
After this method is called, self.connection_file contains the *full path*
to the connection file, never just its name.
Paul Ivanov
refactoring common code out of qtconsole
r5603 """
if self.existing:
try:
cf = find_connection_file(self.existing)
except Exception:
self.log.critical("Could not find existing kernel connection file %s", self.existing)
self.exit(1)
MinRK
adjustments to notebook app logging...
r14645 self.log.debug("Connecting to existing kernel: %s" % cf)
Paul Ivanov
refactoring common code out of qtconsole
r5603 self.connection_file = cf
MinRK
improve cleanup of connection files...
r5609 else:
# not existing, check if we are going to write the file
# and ensure that self.connection_file is a full path, not just the shortname
try:
cf = find_connection_file(self.connection_file)
except Exception:
# file might not exist
if self.connection_file == os.path.basename(self.connection_file):
# just shortname, put it in security dir
cf = os.path.join(self.profile_dir.security_dir, self.connection_file)
else:
cf = self.connection_file
self.connection_file = cf
Paul Ivanov
remove load_connection_file from consoleapp...
r16497 try:
self.connection_file = filefind(self.connection_file, ['.', self.profile_dir.security_dir])
except IOError:
self.log.debug("Connection File not found: %s", self.connection_file)
return
MinRK
improve cleanup of connection files...
r5609
Paul Ivanov
refactoring common code out of qtconsole
r5603 # should load_connection_file only be used for existing?
# as it is now, this allows reusing ports if an existing
# file is requested
try:
self.load_connection_file()
except Exception:
self.log.error("Failed to load connection file: %r", self.connection_file, exc_info=True)
self.exit(1)
def init_ssh(self):
"""set up ssh tunnels, if needed."""
MinRK
ip/transport live in KernelManager now...
r9177 if not self.existing or (not self.sshserver and not self.sshkey):
Paul Ivanov
refactoring common code out of qtconsole
r5603 return
MinRK
ip/transport live in KernelManager now...
r9177 self.load_connection_file()
MinRK
fix `--existing` with non-localhost IP...
r12110 transport = self.transport
ip = self.ip
MinRK
ip/transport live in KernelManager now...
r9177
if transport != 'tcp':
self.log.error("Can only use ssh tunnels with TCP sockets, not %s", transport)
sys.exit(-1)
MinRK
enable IPC transport for kernels...
r7321
Paul Ivanov
refactoring common code out of qtconsole
r5603 if self.sshkey and not self.sshserver:
# specifying just the key implies that we are connecting directly
MinRK
ip/transport live in KernelManager now...
r9177 self.sshserver = ip
MinRK
avoid executing code in utils.localinterfaces at import time...
r12591 ip = localhost()
Paul Ivanov
refactoring common code out of qtconsole
r5603
# build connection dict for tunnels:
MinRK
ip/transport live in KernelManager now...
r9177 info = dict(ip=ip,
Paul Ivanov
refactoring common code out of qtconsole
r5603 shell_port=self.shell_port,
iopub_port=self.iopub_port,
stdin_port=self.stdin_port,
hb_port=self.hb_port
)
MinRK
ip/transport live in KernelManager now...
r9177 self.log.info("Forwarding connections to %s via %s"%(ip, self.sshserver))
Paul Ivanov
refactoring common code out of qtconsole
r5603
# tunnels return a new set of ports, which will be on localhost:
MinRK
avoid executing code in utils.localinterfaces at import time...
r12591 self.ip = localhost()
Paul Ivanov
refactoring common code out of qtconsole
r5603 try:
newports = tunnel_to_kernel(info, self.sshserver, self.sshkey)
except:
# even catch KeyboardInterrupt
self.log.error("Could not setup tunnels", exc_info=True)
self.exit(1)
self.shell_port, self.iopub_port, self.stdin_port, self.hb_port = newports
cf = self.connection_file
base,ext = os.path.splitext(cf)
base = os.path.basename(base)
self.connection_file = os.path.basename(base)+'-ssh'+ext
MinRK
adjustments to notebook app logging...
r14645 self.log.info("To connect another client via this tunnel, use:")
self.log.info("--existing %s" % self.connection_file)
Paul Ivanov
refactoring common code out of qtconsole
r5603
def _new_connection_file(self):
MinRK
improve cleanup of connection files...
r5609 cf = ''
while not cf:
# we don't need a 128b id to distinguish kernels, use more readable
# 48b node segment (12 hex chars). Users running more than 32k simultaneous
# kernels can subclass.
ident = str(uuid.uuid4()).split('-')[-1]
cf = os.path.join(self.profile_dir.security_dir, 'kernel-%s.json' % ident)
# only keep if it's actually new. Protect against unlikely collision
# in 48b random search space
cf = cf if not os.path.exists(cf) else ''
return cf
Paul Ivanov
refactoring common code out of qtconsole
r5603
def init_kernel_manager(self):
# Don't let Qt or ZMQ swallow KeyboardInterupts.
MinRK
update terminal console to new KM / KC APIs
r10287 if self.existing:
self.kernel_manager = None
return
Paul Ivanov
refactoring common code out of qtconsole
r5603 signal.signal(signal.SIGINT, signal.SIG_DFL)
# Create a KernelManager and start a kernel.
Thomas Kluyver
Nicer error message when kernel is not found
r16383 try:
self.kernel_manager = self.kernel_manager_class(
ip=self.ip,
MinRK
fix Session inheritance for frontends with `--existing`...
r17166 session=self.session,
Thomas Kluyver
Nicer error message when kernel is not found
r16383 transport=self.transport,
shell_port=self.shell_port,
iopub_port=self.iopub_port,
stdin_port=self.stdin_port,
hb_port=self.hb_port,
connection_file=self.connection_file,
kernel_name=self.kernel_name,
parent=self,
ipython_dir=self.ipython_dir,
)
except NoSuchKernel:
self.log.critical("Could not find kernel %s", self.kernel_name)
self.exit(1)
MinRK
use KM.client() method in ConsoleApp
r10307 self.kernel_manager.client_factory = self.kernel_client_class
Min RK
Don't pass IPython-specific args to non-IPython kernels...
r18933 # FIXME: remove special treatment of IPython kernels
kwargs = {}
if self.kernel_manager.ipython_kernel:
kwargs['extra_arguments'] = self.kernel_argv
self.kernel_manager.start_kernel(**kwargs)
MinRK
use KM.client() method in ConsoleApp
r10307 atexit.register(self.kernel_manager.cleanup_ipc_files)
if self.sshserver:
Paul Ivanov
refactoring common code out of qtconsole
r5603 # ssh, write new connection file
self.kernel_manager.write_connection_file()
MinRK
update terminal console to new KM / KC APIs
r10287
# in case KM defaults / ssh writing changes things:
km = self.kernel_manager
self.shell_port=km.shell_port
self.iopub_port=km.iopub_port
self.stdin_port=km.stdin_port
self.hb_port=km.hb_port
self.connection_file = km.connection_file
MinRK
improve cleanup of connection files...
r5609 atexit.register(self.kernel_manager.cleanup_connection_file)
MinRK
update terminal console to new KM / KC APIs
r10287
def init_kernel_client(self):
MinRK
use KM.client() method in ConsoleApp
r10307 if self.kernel_manager is not None:
self.kernel_client = self.kernel_manager.client()
else:
self.kernel_client = self.kernel_client_class(
MinRK
fix Session inheritance for frontends with `--existing`...
r17166 session=self.session,
MinRK
fix `--existing` with non-localhost IP...
r12110 ip=self.ip,
transport=self.transport,
MinRK
update terminal console to new KM / KC APIs
r10287 shell_port=self.shell_port,
iopub_port=self.iopub_port,
stdin_port=self.stdin_port,
hb_port=self.hb_port,
connection_file=self.connection_file,
MinRK
use `parent=self` throughout IPython...
r11064 parent=self,
MinRK
use KM.client() method in ConsoleApp
r10307 )
MinRK
update terminal console to new KM / KC APIs
r10287
self.kernel_client.start_channels()
Paul Ivanov
refactoring common code out of qtconsole
r5603
def initialize(self, argv=None):
Paul Ivanov
zmqterminal now uses the zmq mixin app
r5604 """
Classes which mix this class in should call:
MinRK
rename IPythonMixinConsoleApp to IPythonConsoleApp...
r5618 IPythonConsoleApp.initialize(self,argv)
Paul Ivanov
zmqterminal now uses the zmq mixin app
r5604 """
Paul Ivanov
refactoring common code out of qtconsole
r5603 self.init_connection_file()
default_secure(self.config)
self.init_ssh()
self.init_kernel_manager()
MinRK
update terminal console to new KM / KC APIs
r10287 self.init_kernel_client()
Paul Ivanov
refactoring common code out of qtconsole
r5603