##// END OF EJS Templates
Fix ultratb when there are non-ascii filenames present in a traceback...
Fix ultratb when there are non-ascii filenames present in a traceback This solves the simple problem of running a file with non-ascii chars in its name that contains an error of any kind in it.

File last commit:

r19452:fe5dd275 merge
r19858:31b4e819
Show More
manager.py
442 lines | 14.9 KiB | text/x-python | PythonLexer
MinRK
avoid executing code in utils.localinterfaces at import time...
r12591 """Base class to manage a running kernel"""
Brian Granger
Work on the kernel manager.
r2606
Thomas Kluyver
Add mechanism to specify environment variables in kernel spec
r16349 # Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
Brian Granger
Kernel manager is cleaned up and simplified. Still bugs though.
r2699
MinRK
mv IPython.zmq to IPython.kernel.zmq
r9372 from __future__ import absolute_import
Thomas Kluyver
Create run_kernel context manager
r17821 from contextlib import contextmanager
Thomas Kluyver
Add mechanism to specify environment variables in kernel spec
r16349 import os
MinRK
use simple replacement rather than string formatting in format_kernel_cmd...
r12873 import re
epatters
Implemented kernel interrupts for Windows.
r3027 import signal
epatters
Adding some temporary hacks to work around (Py)ZMQ bugs on Windows.
r2995 import sys
epatters
Added a flush method to the SubSocketChannel. The Qt console frontend now uses this method to ensure that output has been processed before it writes a new prompt.
r2614 import time
Thomas Kluyver
Start refactoring KernelManager to use kernel registry
r16263 import warnings
Thomas Kluyver
Create run_kernel context manager
r17821 try:
from queue import Empty # Py 3
except ImportError:
from Queue import Empty # Py 2
Brian Granger
Work on the kernel manager.
r2606
import zmq
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611
MinRK
add `KernelManager.client()`
r10300 from IPython.utils.importstring import import_item
MinRK
avoid executing code in utils.localinterfaces at import time...
r12591 from IPython.utils.localinterfaces import is_local_ip, local_ips
Thomas Kluyver
Allow IPython directory to be passed down to kernel selection from App...
r16382 from IPython.utils.path import get_ipython_dir
MinRK
use connection files instead of ports to connect to kernels...
r4958 from IPython.utils.traitlets import (
MinRK
add `KernelManager.client()`
r10300 Any, Instance, Unicode, List, Bool, Type, DottedObjectName
MinRK
use connection files instead of ports to connect to kernels...
r4958 )
MinRK
move utils.kernel (formerly entry_point and lib.kernel) to kernel.util
r9353 from IPython.kernel import (
MinRK
allow custom kernel_cmd in KernelManager
r9348 launch_kernel,
Thomas Kluyver
Start refactoring KernelManager to use kernel registry
r16263 kernelspec,
MinRK
allow custom kernel_cmd in KernelManager
r9348 )
MinRK
split KernelManager into KernelManager + KernelClient
r10285 from .connect import ConnectionFileMixin
MinRK
define and test IPython.kernel public API
r9376 from .zmq.session import Session
MinRK
update imports with new layout
r10284 from .managerabc import (
Brian Granger
Creating an ABC for kernel managers and channels.
r9121 KernelManagerABC
)
Brian Granger
Kernel manager is cleaned up and simplified. Still bugs though.
r2699
MinRK
ConnectionFileMixin is a LoggingConfigurable
r16732 class KernelManager(ConnectionFileMixin):
MinRK
split KernelManager into KernelManager + KernelClient
r10285 """Manages a single kernel in a subprocess on this host.
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
split KernelManager into KernelManager + KernelClient
r10285 This version starts kernels with Popen.
epatters
Cleaned up KernelManager interface and clarified documentation.
r2631 """
MinRK
split KernelManager into KernelManager + KernelClient
r10285
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611 # The PyZMQ Context to use for communication with the kernel.
MinRK
finish plumbing config to Session objects...
r4015 context = Instance(zmq.Context)
def _context_default(self):
return zmq.Context.instance()
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611
MinRK
add `KernelManager.client()`
r10300 # the class to create with our `client` method
MinRK
make BlockingKernelClient the default Client...
r10384 client_class = DottedObjectName('IPython.kernel.blocking.BlockingKernelClient')
MinRK
add `KernelManager.client()`
r10300 client_factory = Type()
def _client_class_changed(self, name, old, new):
self.client_factory = import_item(str(new))
epatters
* Change input mechanism: replace raw_input instead of stdin....
r2730 # The kernel process with which the KernelManager is communicating.
MinRK
allow custom kernel_cmd in KernelManager
r9348 # generally a Popen instance
MinRK
relocate redundantly-named kernel files...
r10283 kernel = Any()
Thomas Kluyver
Start refactoring KernelManager to use kernel registry
r16263
Thomas Kluyver
Allow IPython directory to be passed down to kernel selection from App...
r16382 kernel_spec_manager = Instance(kernelspec.KernelSpecManager)
def _kernel_spec_manager_default(self):
return kernelspec.KernelSpecManager(ipython_dir=self.ipython_dir)
Thomas Kluyver
Change displayed kernel name when our session is started
r17371 kernel_name = Unicode(kernelspec.NATIVE_KERNEL_NAME)
Thomas Kluyver
Start refactoring KernelManager to use kernel registry
r16263
kernel_spec = Instance(kernelspec.KernelSpec)
def _kernel_spec_default(self):
Thomas Kluyver
Allow IPython directory to be passed down to kernel selection from App...
r16382 return self.kernel_spec_manager.get_kernel_spec(self.kernel_name)
Thomas Kluyver
Start refactoring KernelManager to use kernel registry
r16263
def _kernel_name_changed(self, name, old, new):
Thomas Kluyver
Change displayed kernel name when our session is started
r17371 if new == 'python':
self.kernel_name = kernelspec.NATIVE_KERNEL_NAME
# This triggered another run of this function, so we can exit now
return
Thomas Kluyver
Allow IPython directory to be passed down to kernel selection from App...
r16382 self.kernel_spec = self.kernel_spec_manager.get_kernel_spec(new)
Thomas Kluyver
Special cased kernel name is 'python', not 'native'
r16333 self.ipython_kernel = new in {'python', 'python2', 'python3'}
MinRK
relocate redundantly-named kernel files...
r10283
MinRK
allow custom kernel_cmd in KernelManager
r9348 kernel_cmd = List(Unicode, config=True,
Thomas Kluyver
Start refactoring KernelManager to use kernel registry
r16263 help="""DEPRECATED: Use kernel_name instead.
The Popen Command to launch the kernel.
Konrad Hinsen
More detailed documentation about kernel_comd documentation
r14820 Override this if you have a custom kernel.
If kernel_cmd is specified in a configuration file,
IPython does not pass any arguments to the kernel,
because it cannot make any assumptions about the
arguments that the kernel understands. In particular,
this means that the kernel does not receive the
option --debug if it given on the IPython command line.
MinRK
allow custom kernel_cmd in KernelManager
r9348 """
)
Brian Granger
Refactoring kernel restarting.
r10282
MinRK
allow custom kernel_cmd in KernelManager
r9348 def _kernel_cmd_changed(self, name, old, new):
Thomas Kluyver
Start refactoring KernelManager to use kernel registry
r16263 warnings.warn("Setting kernel_cmd is deprecated, use kernel_spec to "
"start different kernels.")
MinRK
allow custom kernel_cmd in KernelManager
r9348 self.ipython_kernel = False
ipython_kernel = Bool(True)
Thomas Kluyver
Allow IPython directory to be passed down to kernel selection from App...
r16382
ipython_dir = Unicode()
def _ipython_dir_default(self):
return get_ipython_dir()
epatters
* Change input mechanism: replace raw_input instead of stdin....
r2730
MinRK
split KernelManager into KernelManager + KernelClient
r10285 # Protected traits
MinRK
add control channel...
r10296 _launch_args = Any()
_control_socket = Any()
MinRK
improve default ipc file locations...
r9175
MinRK
KM.client creates a client with a shared Session
r10309 _restarter = Any()
Brian Granger
Refactoring kernel restarting.
r10282 autorestart = Bool(False, config=True,
help="""Should we autorestart the kernel if it dies."""
)
MinRK
improve default ipc file locations...
r9175 def __del__(self):
MinRK
add control channel...
r10296 self._close_control_socket()
Brian E. Granger
Putting connection file cleanup back in __del__.
r9154 self.cleanup_connection_file()
Brian E. Granger
Removing connection/ipc file cleanup from KernelManager.__del__.
r9152
epatters
* The SVG payload matplotlib backend now works....
r2758 #--------------------------------------------------------------------------
Brian Granger
Refactoring kernel restarting.
r10282 # Kernel restarter
#--------------------------------------------------------------------------
def start_restarter(self):
pass
def stop_restarter(self):
pass
MinRK
expose restart callbacks via KernelManager
r10313 def add_restart_callback(self, callback, event='restart'):
"""register a callback to be called when a kernel is restarted"""
if self._restarter is None:
return
self._restarter.add_callback(callback, event)
def remove_restart_callback(self, callback, event='restart'):
"""unregister a callback to be called when a kernel is restarted"""
if self._restarter is None:
return
self._restarter.remove_callback(callback, event)
Brian Granger
Refactoring kernel restarting.
r10282 #--------------------------------------------------------------------------
MinRK
add `KernelManager.client()`
r10300 # create a Client connected to our Kernel
#--------------------------------------------------------------------------
def client(self, **kwargs):
"""Create a client configured to connect to our kernel"""
if self.client_factory is None:
self.client_factory = import_item(self.client_class)
kw = {}
kw.update(self.get_connection_info())
MinRK
KM.client creates a client with a shared Session
r10309 kw.update(dict(
connection_file=self.connection_file,
session=self.session,
MinRK
use `parent=self` throughout IPython...
r11064 parent=self,
MinRK
KM.client creates a client with a shared Session
r10309 ))
MinRK
add `KernelManager.client()`
r10300
# add kwargs last, for manual overrides
kw.update(kwargs)
return self.client_factory(**kw)
#--------------------------------------------------------------------------
Brian E. Granger
Final cleanup of kernelmanager...
r9151 # Kernel management
Brian Granger
Creating an ABC for kernel managers and channels.
r9121 #--------------------------------------------------------------------------
Brian Granger
Refactoring kernel restarting.
r10282
Thomas Kluyver
Simplify kernel manager code
r17748 def format_kernel_cmd(self, extra_arguments=None):
MinRK
use simple replacement rather than string formatting in format_kernel_cmd...
r12873 """replace templated args (e.g. {connection_file})"""
Thomas Kluyver
Simplify kernel manager code
r17748 extra_arguments = extra_arguments or []
MinRK
allow custom kernel_cmd in KernelManager
r9348 if self.kernel_cmd:
Thomas Kluyver
Simplify kernel manager code
r17748 cmd = self.kernel_cmd + extra_arguments
Thomas Kluyver
Start refactoring KernelManager to use kernel registry
r16263 else:
Thomas Kluyver
Simplify kernel manager code
r17748 cmd = self.kernel_spec.argv + extra_arguments
Thomas Kluyver
Start refactoring KernelManager to use kernel registry
r16263
MinRK
allow custom kernel_cmd in KernelManager
r9348 ns = dict(connection_file=self.connection_file)
ns.update(self._launch_args)
MinRK
use simple replacement rather than string formatting in format_kernel_cmd...
r12873
pat = re.compile(r'\{([A-Za-z0-9_]+)\}')
def from_ns(match):
"""Get the key out of ns if it's there, otherwise no change."""
return ns.get(match.group(1), match.group())
return [ pat.sub(from_ns, arg) for arg in cmd ]
MinRK
relocate redundantly-named kernel files...
r10283
MinRK
allow KM._launch_kernel to be overridden in subclasses
r9349 def _launch_kernel(self, kernel_cmd, **kw):
"""actually launch the kernel
MinRK
relocate redundantly-named kernel files...
r10283
MinRK
allow KM._launch_kernel to be overridden in subclasses
r9349 override in a subclass to launch kernel subprocesses differently
"""
return launch_kernel(kernel_cmd, **kw)
MinRK
relocate redundantly-named kernel files...
r10283
MinRK
add `KernelManager.client()`
r10300 # Control socket used for polite kernel shutdown
MinRK
add control channel...
r10296 def _connect_control_socket(self):
if self._control_socket is None:
self._control_socket = self.connect_control()
MinRK
add `KernelManager.client()`
r10300 self._control_socket.linger = 100
MinRK
add control channel...
r10296
def _close_control_socket(self):
if self._control_socket is None:
return
self._control_socket.close()
self._control_socket = None
epatters
First cut at allowing the kernel to be restarted from the frontend.
r2851 def start_kernel(self, **kw):
Brian E. Granger
More kernelmanager docstring cleanup.
r9129 """Starts a kernel on this host in a separate process.
epatters
* Implemented KernelManager's 'signal_kernel' method....
r2686
Brian Granger
Kernel manager is cleaned up and simplified. Still bugs though.
r2699 If random ports (port=0) are being used, this method must be called
before the channels are created.
epatters
* The SVG payload matplotlib backend now works....
r2758
Thomas Kluyver
Clean up numpydoc section headers
r13587 Parameters
----------
epatters
Make 'restart_kernel' method more convenient + docstring improvements.
r3784 **kw : optional
MinRK
move IPython.zmq.entry_point to IPython.utils.kernel
r9352 keyword arguments that are passed down to build the kernel_cmd
and launching the kernel (e.g. Popen kwargs).
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611 """
MinRK
avoid executing code in utils.localinterfaces at import time...
r12591 if self.transport == 'tcp' and not is_local_ip(self.ip):
MinRK
Possible fix for GH-169
r3144 raise RuntimeError("Can only launch a kernel on a local interface. "
epatters
* Implemented a proper main() function for kernel.py that reads command line input....
r2667 "Make sure that the '*_address' attributes are "
MinRK
Possible fix for GH-169
r3144 "configured properly. "
MinRK
avoid executing code in utils.localinterfaces at import time...
r12591 "Currently valid addresses are: %s" % local_ips()
MinRK
Possible fix for GH-169
r3144 )
MinRK
relocate redundantly-named kernel files...
r10283
MinRK
use connection files instead of ports to connect to kernels...
r4958 # write connection file / get default ports
self.write_connection_file()
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
allow custom kernel_cmd in KernelManager
r9348 # save kwargs for use in restart
epatters
First cut at allowing the kernel to be restarted from the frontend.
r2851 self._launch_args = kw.copy()
MinRK
allow custom kernel_cmd in KernelManager
r9348 # build the Popen cmd
Thomas Kluyver
Simplify kernel manager code
r17748 extra_arguments = kw.pop('extra_arguments', [])
kernel_cmd = self.format_kernel_cmd(extra_arguments=extra_arguments)
Thomas Kluyver
Add mechanism to specify environment variables in kernel spec
r16349 if self.kernel_cmd:
# If kernel_cmd has been set manually, don't refer to a kernel spec
env = os.environ
else:
# Environment variables from kernel spec are added to os.environ
env = os.environ.copy()
env.update(self.kernel_spec.env or {})
MinRK
allow custom kernel_cmd in KernelManager
r9348 # launch the kernel subprocess
Thomas Kluyver
Add mechanism to specify environment variables in kernel spec
r16349 self.kernel = self._launch_kernel(kernel_cmd, env=env,
MinRK
allow KM._launch_kernel to be overridden in subclasses
r9349 **kw)
Brian Granger
Refactoring kernel restarting.
r10282 self.start_restarter()
MinRK
add control channel...
r10296 self._connect_control_socket()
epatters
* Implemented KernelManager's 'signal_kernel' method....
r2686
Thomas Kluyver
Shut down kernels in parallel...
r16510 def request_shutdown(self, restart=False):
"""Send a shutdown request via control channel
On Windows, this just kills kernels instead, because the shutdown
messages don't work.
"""
MinRK
add control channel...
r10296 content = dict(restart=restart)
msg = self.session.msg("shutdown_request", content=content)
self.session.send(self._control_socket, msg)
MinRK
split KernelManager into KernelManager + KernelClient
r10285
Thomas Kluyver
Rename wait_shutdown to finish_shutdown
r16523 def finish_shutdown(self, waittime=1, pollinterval=0.1):
Thomas Kluyver
Shut down kernels in parallel...
r16510 """Wait for kernel shutdown, then kill process if it doesn't shutdown.
This does not send shutdown requests - use :meth:`request_shutdown`
first.
"""
Thomas Kluyver
Rename wait_shutdown to finish_shutdown
r16523 for i in range(int(waittime/pollinterval)):
Thomas Kluyver
Shut down kernels in parallel...
r16510 if self.is_alive():
Thomas Kluyver
Rename wait_shutdown to finish_shutdown
r16523 time.sleep(pollinterval)
Thomas Kluyver
Shut down kernels in parallel...
r16510 else:
break
else:
# OK, we've waited long enough.
if self.has_kernel:
self._kill_kernel()
Thomas Kluyver
Simplify KernelManager.cleanup()
r16515 def cleanup(self, connection_file=True):
Thomas Kluyver
Shut down kernels in parallel...
r16510 """Clean up resources when the kernel is shut down"""
Thomas Kluyver
Simplify KernelManager.cleanup()
r16515 if connection_file:
Thomas Kluyver
Shut down kernels in parallel...
r16510 self.cleanup_connection_file()
Thomas Kluyver
Simplify KernelManager.cleanup()
r16515 self.cleanup_ipc_files()
Thomas Kluyver
Shut down kernels in parallel...
r16510 self._close_control_socket()
Brian Granger
Fixing bug in cleanup of ipc files and adding new to shutdown....
r9119 def shutdown_kernel(self, now=False, restart=False):
MinRK
relocate redundantly-named kernel files...
r10283 """Attempts to the stop the kernel process cleanly.
Brian E. Granger
More kernelmanager docstring cleanup.
r9129
This attempts to shutdown the kernels cleanly by:
1. Sending it a shutdown message over the shell channel.
2. If that fails, the kernel is shutdown forcibly by sending it
a signal.
epatters
BUG: Block until kernel termination after sending a kill signal.
r8487
Thomas Kluyver
Clean up numpydoc section headers
r13587 Parameters
----------
Brian E. Granger
More kernelmanager docstring cleanup.
r9129 now : bool
Should the kernel be forcible killed *now*. This skips the
first, nice shutdown attempt.
restart: bool
Will this kernel be restarted after it is shutdown. When this
is True, connection files will not be cleaned up.
epatters
* Moved shutdown_kernel method from FrontendWidget to KernelManager....
r2961 """
Brian Granger
Refactoring kernel restarting.
r10282 # Stop monitoring for restarting while we shutdown.
self.stop_restarter()
Thomas Kluyver
Shut down kernels in parallel...
r16510 if now:
self._kill_kernel()
Brian Granger
Fixing bug in cleanup of ipc files and adding new to shutdown....
r9119 else:
Thomas Kluyver
Shut down kernels in parallel...
r16510 self.request_shutdown(restart=restart)
Brian Granger
Fixing bug in cleanup of ipc files and adding new to shutdown....
r9119 # Don't send any additional kernel kill messages immediately, to give
# the kernel a chance to properly execute shutdown actions. Wait for at
# most 1s, checking every 0.1s.
Thomas Kluyver
Rename wait_shutdown to finish_shutdown
r16523 self.finish_shutdown()
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Simplify KernelManager.cleanup()
r16515 self.cleanup(connection_file=not restart)
MinRK
use connection files instead of ports to connect to kernels...
r4958
epatters
Make 'restart_kernel' method more convenient + docstring improvements.
r3784 def restart_kernel(self, now=False, **kw):
"""Restarts a kernel with the arguments that were used to launch it.
Bernardo B. Marques
remove all trailling spaces
r4872
epatters
Make 'restart_kernel' method more convenient + docstring improvements.
r3784 If the old kernel was launched with random ports, the same ports will be
Brian E. Granger
More kernelmanager docstring cleanup.
r9129 used for the new kernel. The same connection file is used again.
Fernando Perez
Added kernel shutdown support: messaging spec, zmq and client code ready....
r2972
Parameters
----------
Fernando Perez
Rename 'instant_death' to 'now' as per code review.
r3030 now : bool, optional
epatters
Make 'restart_kernel' method more convenient + docstring improvements.
r3784 If True, the kernel is forcefully restarted *immediately*, without
having a chance to do any cleanup action. Otherwise the kernel is
given 1s to clean up before a forceful restart is issued.
Fernando Perez
Added kernel shutdown support: messaging spec, zmq and client code ready....
r2972
epatters
Make 'restart_kernel' method more convenient + docstring improvements.
r3784 In all cases the kernel is restarted, the only difference is whether
it is given a chance to perform a clean shutdown or not.
**kw : optional
Brian E. Granger
More kernelmanager docstring cleanup.
r9129 Any options specified here will overwrite those used to launch the
epatters
Make 'restart_kernel' method more convenient + docstring improvements.
r3784 kernel.
epatters
First cut at allowing the kernel to be restarted from the frontend.
r2851 """
if self._launch_args is None:
raise RuntimeError("Cannot restart the kernel. "
"No previous call to 'start_kernel'.")
else:
epatters
Make 'restart_kernel' method more convenient + docstring improvements.
r3784 # Stop currently running kernel.
Brian Granger
Fixing bug in cleanup of ipc files and adding new to shutdown....
r9119 self.shutdown_kernel(now=now, restart=True)
epatters
Make 'restart_kernel' method more convenient + docstring improvements.
r3784
# Start new kernel.
self._launch_args.update(kw)
epatters
* Fixed heartbeat thread not stopping cleanly....
r2915 self.start_kernel(**self._launch_args)
epatters
First cut at allowing the kernel to be restarted from the frontend.
r2851
epatters
* Implemented KernelManager's 'signal_kernel' method....
r2686 @property
def has_kernel(self):
Brian E. Granger
More kernelmanager docstring cleanup.
r9129 """Has a kernel been started that we are managing."""
epatters
* Change input mechanism: replace raw_input instead of stdin....
r2730 return self.kernel is not None
epatters
* Implemented KernelManager's 'signal_kernel' method....
r2686
Brian E. Granger
Make KernelManager.kill_kernel private....
r9130 def _kill_kernel(self):
Brian E. Granger
More kernelmanager docstring cleanup.
r9129 """Kill the running kernel.
epatters
BUG: Block until kernel termination after sending a kill signal.
r8487
Brian E. Granger
More kernelmanager docstring cleanup.
r9129 This is a private method, callers should use shutdown_kernel(now=True).
epatters
BUG: Block until kernel termination after sending a kill signal.
r8487 """
Brian Granger
Fixed inconsistent usage of has_kernel in KernelManager.
r3026 if self.has_kernel:
epatters
Integrated the heart beat pausing/unpausing logic with the (Qt)KernelManager.
r3032
epatters
BUG: Block until kernel termination after sending a kill signal.
r8487 # Signal the kernel to terminate (sends SIGKILL on Unix and calls
# TerminateProcess() on Win32).
epatters
Safe kernel killing in Windows.
r3034 try:
self.kernel.kill()
Matthias BUSSONNIER
conform to pep 3110...
r7787 except OSError as e:
epatters
Safe kernel killing in Windows.
r3034 # In Windows, we will get an Access Denied error if the process
# has already terminated. Ignore it.
epatters
Handle Unix ESRCH errors gracefully in kill_kernel.
r3827 if sys.platform == 'win32':
if e.winerror != 5:
raise
# On Unix, we may get an ESRCH error if the process has already
# terminated. Ignore it.
else:
from errno import ESRCH
if e.errno != ESRCH:
raise
epatters
BUG: Block until kernel termination after sending a kill signal.
r8487
# Block until the kernel terminates.
self.kernel.wait()
epatters
* Change input mechanism: replace raw_input instead of stdin....
r2730 self.kernel = None
epatters
Added 'start_listening' and 'stop_listening' methods to the kernel manager.
r2639 else:
epatters
* Implemented KernelManager's 'signal_kernel' method....
r2686 raise RuntimeError("Cannot kill kernel. No kernel is running!")
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611
epatters
Implemented kernel interrupts for Windows.
r3027 def interrupt_kernel(self):
Brian E. Granger
More kernelmanager docstring cleanup.
r9129 """Interrupts the kernel by sending it a signal.
epatters
BUG: Block until kernel termination after sending a kill signal.
r8487
Unlike ``signal_kernel``, this operation is well supported on all
platforms.
epatters
Implemented kernel interrupts for Windows.
r3027 """
if self.has_kernel:
if sys.platform == 'win32':
Thomas Kluyver
Correct import for kernelmanager on Windows
r9487 from .zmq.parentpoller import ParentPollerWindows as Poller
epatters
Implemented kernel interrupts for Windows.
r3027 Poller.send_interrupt(self.kernel.win32_interrupt_event)
else:
self.kernel.send_signal(signal.SIGINT)
else:
raise RuntimeError("Cannot interrupt kernel. No kernel is running!")
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611 def signal_kernel(self, signum):
Brian E. Granger
More kernelmanager docstring cleanup.
r9129 """Sends a signal to the kernel.
epatters
BUG: Block until kernel termination after sending a kill signal.
r8487
Note that since only SIGTERM is supported on Windows, this function is
only useful on Unix systems.
epatters
Implemented kernel interrupts for Windows.
r3027 """
Brian Granger
Fixed inconsistent usage of has_kernel in KernelManager.
r3026 if self.has_kernel:
epatters
* Change input mechanism: replace raw_input instead of stdin....
r2730 self.kernel.send_signal(signum)
epatters
* Implemented KernelManager's 'signal_kernel' method....
r2686 else:
raise RuntimeError("Cannot signal kernel. No kernel is running!")
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611
Brian Granger
Kernel manager is cleaned up and simplified. Still bugs though.
r2699 def is_alive(self):
"""Is the kernel process still running?"""
Brian Granger
Fixed inconsistent usage of has_kernel in KernelManager.
r3026 if self.has_kernel:
epatters
* Change input mechanism: replace raw_input instead of stdin....
r2730 if self.kernel.poll() is None:
Brian Granger
Kernel manager is cleaned up and simplified. Still bugs though.
r2699 return True
else:
return False
else:
MinRK
split KernelManager into KernelManager + KernelClient
r10285 # we don't have a kernel
return False
Brian Granger
Kernel manager is cleaned up and simplified. Still bugs though.
r2699
Brian Granger
Creating an ABC for kernel managers and channels.
r9121 KernelManagerABC.register(KernelManager)
MinRK
split KernelManager into KernelManager + KernelClient
r10285
Thomas Kluyver
Create run_kernel context manager
r17821
def start_new_kernel(startup_timeout=60, kernel_name='python', **kwargs):
"""Start a new kernel, and return its Manager and Client"""
km = KernelManager(kernel_name=kernel_name)
km.start_kernel(**kwargs)
kc = km.client()
kc.start_channels()
Thomas Kluyver
Move kernel_info for adaptation onto KernelClient
r19216 kc.wait_for_ready()
Thomas Kluyver
Create run_kernel context manager
r17821
return km, kc
@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)