You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

606 lines
21 KiB

4 years ago
  1. # -*- coding: utf-8 -*-
  2. """A ZMQ-based subclass of InteractiveShell.
  3. This code is meant to ease the refactoring of the base InteractiveShell into
  4. something with a cleaner architecture for 2-process use, without actually
  5. breaking InteractiveShell itself. So we're doing something a bit ugly, where
  6. we subclass and override what we want to fix. Once this is working well, we
  7. can go back to the base class and refactor the code for a cleaner inheritance
  8. implementation that doesn't rely on so much monkeypatching.
  9. But this lets us maintain a fully working IPython as we develop the new
  10. machinery. This should thus be thought of as scaffolding.
  11. """
  12. # Copyright (c) IPython Development Team.
  13. # Distributed under the terms of the Modified BSD License.
  14. from __future__ import print_function
  15. import os
  16. import sys
  17. import time
  18. import warnings
  19. from threading import local
  20. from tornado import ioloop
  21. from IPython.core.interactiveshell import (
  22. InteractiveShell, InteractiveShellABC
  23. )
  24. from IPython.core import page
  25. from IPython.core.autocall import ZMQExitAutocall
  26. from IPython.core.displaypub import DisplayPublisher
  27. from IPython.core.error import UsageError
  28. from IPython.core.magics import MacroToEdit, CodeMagics
  29. from IPython.core.magic import magics_class, line_magic, Magics
  30. from IPython.core import payloadpage
  31. from IPython.core.usage import default_banner
  32. from IPython.display import display, Javascript
  33. from ipykernel import (
  34. get_connection_file, get_connection_info, connect_qtconsole
  35. )
  36. from IPython.utils import openpy
  37. from ipykernel.jsonutil import json_clean, encode_images
  38. from IPython.utils.process import arg_split
  39. from ipython_genutils import py3compat
  40. from ipython_genutils.py3compat import unicode_type
  41. from traitlets import (
  42. Instance, Type, Dict, CBool, CBytes, Any, default, observe
  43. )
  44. from ipykernel.displayhook import ZMQShellDisplayHook
  45. from jupyter_core.paths import jupyter_runtime_dir
  46. from jupyter_client.session import extract_header, Session
  47. #-----------------------------------------------------------------------------
  48. # Functions and classes
  49. #-----------------------------------------------------------------------------
  50. class ZMQDisplayPublisher(DisplayPublisher):
  51. """A display publisher that publishes data using a ZeroMQ PUB socket."""
  52. session = Instance(Session, allow_none=True)
  53. pub_socket = Any(allow_none=True)
  54. parent_header = Dict({})
  55. topic = CBytes(b'display_data')
  56. # thread_local:
  57. # An attribute used to ensure the correct output message
  58. # is processed. See ipykernel Issue 113 for a discussion.
  59. _thread_local = Any()
  60. def set_parent(self, parent):
  61. """Set the parent for outbound messages."""
  62. self.parent_header = extract_header(parent)
  63. def _flush_streams(self):
  64. """flush IO Streams prior to display"""
  65. sys.stdout.flush()
  66. sys.stderr.flush()
  67. @default('_thread_local')
  68. def _default_thread_local(self):
  69. """Initialize our thread local storage"""
  70. return local()
  71. @property
  72. def _hooks(self):
  73. if not hasattr(self._thread_local, 'hooks'):
  74. # create new list for a new thread
  75. self._thread_local.hooks = []
  76. return self._thread_local.hooks
  77. def publish(self, data, metadata=None, source=None, transient=None,
  78. update=False,
  79. ):
  80. """Publish a display-data message
  81. Parameters
  82. ----------
  83. data: dict
  84. A mime-bundle dict, keyed by mime-type.
  85. metadata: dict, optional
  86. Metadata associated with the data.
  87. transient: dict, optional, keyword-only
  88. Transient data that may only be relevant during a live display,
  89. such as display_id.
  90. Transient data should not be persisted to documents.
  91. update: bool, optional, keyword-only
  92. If True, send an update_display_data message instead of display_data.
  93. """
  94. self._flush_streams()
  95. if metadata is None:
  96. metadata = {}
  97. if transient is None:
  98. transient = {}
  99. self._validate_data(data, metadata)
  100. content = {}
  101. content['data'] = encode_images(data)
  102. content['metadata'] = metadata
  103. content['transient'] = transient
  104. msg_type = 'update_display_data' if update else 'display_data'
  105. # Use 2-stage process to send a message,
  106. # in order to put it through the transform
  107. # hooks before potentially sending.
  108. msg = self.session.msg(
  109. msg_type, json_clean(content),
  110. parent=self.parent_header
  111. )
  112. # Each transform either returns a new
  113. # message or None. If None is returned,
  114. # the message has been 'used' and we return.
  115. for hook in self._hooks:
  116. msg = hook(msg)
  117. if msg is None:
  118. return
  119. self.session.send(
  120. self.pub_socket, msg, ident=self.topic,
  121. )
  122. def clear_output(self, wait=False):
  123. """Clear output associated with the current execution (cell).
  124. Parameters
  125. ----------
  126. wait: bool (default: False)
  127. If True, the output will not be cleared immediately,
  128. instead waiting for the next display before clearing.
  129. This reduces bounce during repeated clear & display loops.
  130. """
  131. content = dict(wait=wait)
  132. self._flush_streams()
  133. self.session.send(
  134. self.pub_socket, u'clear_output', content,
  135. parent=self.parent_header, ident=self.topic,
  136. )
  137. def register_hook(self, hook):
  138. """
  139. Registers a hook with the thread-local storage.
  140. Parameters
  141. ----------
  142. hook : Any callable object
  143. Returns
  144. -------
  145. Either a publishable message, or `None`.
  146. The DisplayHook objects must return a message from
  147. the __call__ method if they still require the
  148. `session.send` method to be called after tranformation.
  149. Returning `None` will halt that execution path, and
  150. session.send will not be called.
  151. """
  152. self._hooks.append(hook)
  153. def unregister_hook(self, hook):
  154. """
  155. Un-registers a hook with the thread-local storage.
  156. Parameters
  157. ----------
  158. hook: Any callable object which has previously been
  159. registered as a hook.
  160. Returns
  161. -------
  162. bool - `True` if the hook was removed, `False` if it wasn't
  163. found.
  164. """
  165. try:
  166. self._hooks.remove(hook)
  167. return True
  168. except ValueError:
  169. return False
  170. @magics_class
  171. class KernelMagics(Magics):
  172. #------------------------------------------------------------------------
  173. # Magic overrides
  174. #------------------------------------------------------------------------
  175. # Once the base class stops inheriting from magic, this code needs to be
  176. # moved into a separate machinery as well. For now, at least isolate here
  177. # the magics which this class needs to implement differently from the base
  178. # class, or that are unique to it.
  179. _find_edit_target = CodeMagics._find_edit_target
  180. @line_magic
  181. def edit(self, parameter_s='', last_call=['','']):
  182. """Bring up an editor and execute the resulting code.
  183. Usage:
  184. %edit [options] [args]
  185. %edit runs an external text editor. You will need to set the command for
  186. this editor via the ``TerminalInteractiveShell.editor`` option in your
  187. configuration file before it will work.
  188. This command allows you to conveniently edit multi-line code right in
  189. your IPython session.
  190. If called without arguments, %edit opens up an empty editor with a
  191. temporary file and will execute the contents of this file when you
  192. close it (don't forget to save it!).
  193. Options:
  194. -n <number>
  195. Open the editor at a specified line number. By default, the IPython
  196. editor hook uses the unix syntax 'editor +N filename', but you can
  197. configure this by providing your own modified hook if your favorite
  198. editor supports line-number specifications with a different syntax.
  199. -p
  200. Call the editor with the same data as the previous time it was used,
  201. regardless of how long ago (in your current session) it was.
  202. -r
  203. Use 'raw' input. This option only applies to input taken from the
  204. user's history. By default, the 'processed' history is used, so that
  205. magics are loaded in their transformed version to valid Python. If
  206. this option is given, the raw input as typed as the command line is
  207. used instead. When you exit the editor, it will be executed by
  208. IPython's own processor.
  209. Arguments:
  210. If arguments are given, the following possibilites exist:
  211. - The arguments are numbers or pairs of colon-separated numbers (like
  212. 1 4:8 9). These are interpreted as lines of previous input to be
  213. loaded into the editor. The syntax is the same of the %macro command.
  214. - If the argument doesn't start with a number, it is evaluated as a
  215. variable and its contents loaded into the editor. You can thus edit
  216. any string which contains python code (including the result of
  217. previous edits).
  218. - If the argument is the name of an object (other than a string),
  219. IPython will try to locate the file where it was defined and open the
  220. editor at the point where it is defined. You can use ``%edit function``
  221. to load an editor exactly at the point where 'function' is defined,
  222. edit it and have the file be executed automatically.
  223. If the object is a macro (see %macro for details), this opens up your
  224. specified editor with a temporary file containing the macro's data.
  225. Upon exit, the macro is reloaded with the contents of the file.
  226. Note: opening at an exact line is only supported under Unix, and some
  227. editors (like kedit and gedit up to Gnome 2.8) do not understand the
  228. '+NUMBER' parameter necessary for this feature. Good editors like
  229. (X)Emacs, vi, jed, pico and joe all do.
  230. - If the argument is not found as a variable, IPython will look for a
  231. file with that name (adding .py if necessary) and load it into the
  232. editor. It will execute its contents with execfile() when you exit,
  233. loading any code in the file into your interactive namespace.
  234. Unlike in the terminal, this is designed to use a GUI editor, and we do
  235. not know when it has closed. So the file you edit will not be
  236. automatically executed or printed.
  237. Note that %edit is also available through the alias %ed.
  238. """
  239. opts,args = self.parse_options(parameter_s, 'prn:')
  240. try:
  241. filename, lineno, _ = CodeMagics._find_edit_target(self.shell, args, opts, last_call)
  242. except MacroToEdit:
  243. # TODO: Implement macro editing over 2 processes.
  244. print("Macro editing not yet implemented in 2-process model.")
  245. return
  246. # Make sure we send to the client an absolute path, in case the working
  247. # directory of client and kernel don't match
  248. filename = os.path.abspath(filename)
  249. payload = {
  250. 'source' : 'edit_magic',
  251. 'filename' : filename,
  252. 'line_number' : lineno
  253. }
  254. self.shell.payload_manager.write_payload(payload)
  255. # A few magics that are adapted to the specifics of using pexpect and a
  256. # remote terminal
  257. @line_magic
  258. def clear(self, arg_s):
  259. """Clear the terminal."""
  260. if os.name == 'posix':
  261. self.shell.system("clear")
  262. else:
  263. self.shell.system("cls")
  264. if os.name == 'nt':
  265. # This is the usual name in windows
  266. cls = line_magic('cls')(clear)
  267. # Terminal pagers won't work over pexpect, but we do have our own pager
  268. @line_magic
  269. def less(self, arg_s):
  270. """Show a file through the pager.
  271. Files ending in .py are syntax-highlighted."""
  272. if not arg_s:
  273. raise UsageError('Missing filename.')
  274. if arg_s.endswith('.py'):
  275. cont = self.shell.pycolorize(openpy.read_py_file(arg_s, skip_encoding_cookie=False))
  276. else:
  277. cont = open(arg_s).read()
  278. page.page(cont)
  279. more = line_magic('more')(less)
  280. # Man calls a pager, so we also need to redefine it
  281. if os.name == 'posix':
  282. @line_magic
  283. def man(self, arg_s):
  284. """Find the man page for the given command and display in pager."""
  285. page.page(self.shell.getoutput('man %s | col -b' % arg_s,
  286. split=False))
  287. @line_magic
  288. def connect_info(self, arg_s):
  289. """Print information for connecting other clients to this kernel
  290. It will print the contents of this session's connection file, as well as
  291. shortcuts for local clients.
  292. In the simplest case, when called from the most recently launched kernel,
  293. secondary clients can be connected, simply with:
  294. $> jupyter <app> --existing
  295. """
  296. try:
  297. connection_file = get_connection_file()
  298. info = get_connection_info(unpack=False)
  299. except Exception as e:
  300. warnings.warn("Could not get connection info: %r" % e)
  301. return
  302. # if it's in the default dir, truncate to basename
  303. if jupyter_runtime_dir() == os.path.dirname(connection_file):
  304. connection_file = os.path.basename(connection_file)
  305. print (info + '\n')
  306. print ("Paste the above JSON into a file, and connect with:\n"
  307. " $> jupyter <app> --existing <file>\n"
  308. "or, if you are local, you can connect with just:\n"
  309. " $> jupyter <app> --existing {0}\n"
  310. "or even just:\n"
  311. " $> jupyter <app> --existing\n"
  312. "if this is the most recent Jupyter kernel you have started.".format(
  313. connection_file
  314. )
  315. )
  316. @line_magic
  317. def qtconsole(self, arg_s):
  318. """Open a qtconsole connected to this kernel.
  319. Useful for connecting a qtconsole to running notebooks, for better
  320. debugging.
  321. """
  322. # %qtconsole should imply bind_kernel for engines:
  323. # FIXME: move to ipyparallel Kernel subclass
  324. if 'ipyparallel' in sys.modules:
  325. from ipyparallel import bind_kernel
  326. bind_kernel()
  327. try:
  328. connect_qtconsole(argv=arg_split(arg_s, os.name=='posix'))
  329. except Exception as e:
  330. warnings.warn("Could not start qtconsole: %r" % e)
  331. return
  332. @line_magic
  333. def autosave(self, arg_s):
  334. """Set the autosave interval in the notebook (in seconds).
  335. The default value is 120, or two minutes.
  336. ``%autosave 0`` will disable autosave.
  337. This magic only has an effect when called from the notebook interface.
  338. It has no effect when called in a startup file.
  339. """
  340. try:
  341. interval = int(arg_s)
  342. except ValueError:
  343. raise UsageError("%%autosave requires an integer, got %r" % arg_s)
  344. # javascript wants milliseconds
  345. milliseconds = 1000 * interval
  346. display(Javascript("IPython.notebook.set_autosave_interval(%i)" % milliseconds),
  347. include=['application/javascript']
  348. )
  349. if interval:
  350. print("Autosaving every %i seconds" % interval)
  351. else:
  352. print("Autosave disabled")
  353. class ZMQInteractiveShell(InteractiveShell):
  354. """A subclass of InteractiveShell for ZMQ."""
  355. displayhook_class = Type(ZMQShellDisplayHook)
  356. display_pub_class = Type(ZMQDisplayPublisher)
  357. data_pub_class = Type('ipykernel.datapub.ZMQDataPublisher')
  358. kernel = Any()
  359. parent_header = Any()
  360. @default('banner1')
  361. def _default_banner1(self):
  362. return default_banner
  363. # Override the traitlet in the parent class, because there's no point using
  364. # readline for the kernel. Can be removed when the readline code is moved
  365. # to the terminal frontend.
  366. colors_force = CBool(True)
  367. readline_use = CBool(False)
  368. # autoindent has no meaning in a zmqshell, and attempting to enable it
  369. # will print a warning in the absence of readline.
  370. autoindent = CBool(False)
  371. exiter = Instance(ZMQExitAutocall)
  372. @default('exiter')
  373. def _default_exiter(self):
  374. return ZMQExitAutocall(self)
  375. @observe('exit_now')
  376. def _update_exit_now(self, change):
  377. """stop eventloop when exit_now fires"""
  378. if change['new']:
  379. loop = self.kernel.io_loop
  380. loop.call_later(0.1, loop.stop)
  381. if self.kernel.eventloop:
  382. exit_hook = getattr(self.kernel.eventloop, 'exit_hook', None)
  383. if exit_hook:
  384. exit_hook(self.kernel)
  385. keepkernel_on_exit = None
  386. # Over ZeroMQ, GUI control isn't done with PyOS_InputHook as there is no
  387. # interactive input being read; we provide event loop support in ipkernel
  388. def enable_gui(self, gui):
  389. from .eventloops import enable_gui as real_enable_gui
  390. try:
  391. real_enable_gui(gui)
  392. self.active_eventloop = gui
  393. except ValueError as e:
  394. raise UsageError("%s" % e)
  395. def init_environment(self):
  396. """Configure the user's environment."""
  397. env = os.environ
  398. # These two ensure 'ls' produces nice coloring on BSD-derived systems
  399. env['TERM'] = 'xterm-color'
  400. env['CLICOLOR'] = '1'
  401. # Since normal pagers don't work at all (over pexpect we don't have
  402. # single-key control of the subprocess), try to disable paging in
  403. # subprocesses as much as possible.
  404. env['PAGER'] = 'cat'
  405. env['GIT_PAGER'] = 'cat'
  406. def init_hooks(self):
  407. super(ZMQInteractiveShell, self).init_hooks()
  408. self.set_hook('show_in_pager', page.as_hook(payloadpage.page), 99)
  409. def init_data_pub(self):
  410. """Delay datapub init until request, for deprecation warnings"""
  411. pass
  412. @property
  413. def data_pub(self):
  414. if not hasattr(self, '_data_pub'):
  415. warnings.warn("InteractiveShell.data_pub is deprecated outside IPython parallel.",
  416. DeprecationWarning, stacklevel=2)
  417. self._data_pub = self.data_pub_class(parent=self)
  418. self._data_pub.session = self.display_pub.session
  419. self._data_pub.pub_socket = self.display_pub.pub_socket
  420. return self._data_pub
  421. @data_pub.setter
  422. def data_pub(self, pub):
  423. self._data_pub = pub
  424. def ask_exit(self):
  425. """Engage the exit actions."""
  426. self.exit_now = (not self.keepkernel_on_exit)
  427. payload = dict(
  428. source='ask_exit',
  429. keepkernel=self.keepkernel_on_exit,
  430. )
  431. self.payload_manager.write_payload(payload)
  432. def run_cell(self, *args, **kwargs):
  433. self._last_traceback = None
  434. return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  435. def _showtraceback(self, etype, evalue, stb):
  436. # try to preserve ordering of tracebacks and print statements
  437. sys.stdout.flush()
  438. sys.stderr.flush()
  439. exc_content = {
  440. u'traceback' : stb,
  441. u'ename' : unicode_type(etype.__name__),
  442. u'evalue' : py3compat.safe_unicode(evalue),
  443. }
  444. dh = self.displayhook
  445. # Send exception info over pub socket for other clients than the caller
  446. # to pick up
  447. topic = None
  448. if dh.topic:
  449. topic = dh.topic.replace(b'execute_result', b'error')
  450. exc_msg = dh.session.send(dh.pub_socket, u'error', json_clean(exc_content),
  451. dh.parent_header, ident=topic)
  452. # FIXME - Once we rely on Python 3, the traceback is stored on the
  453. # exception object, so we shouldn't need to store it here.
  454. self._last_traceback = stb
  455. def set_next_input(self, text, replace=False):
  456. """Send the specified text to the frontend to be presented at the next
  457. input cell."""
  458. payload = dict(
  459. source='set_next_input',
  460. text=text,
  461. replace=replace,
  462. )
  463. self.payload_manager.write_payload(payload)
  464. def set_parent(self, parent):
  465. """Set the parent header for associating output with its triggering input"""
  466. self.parent_header = parent
  467. self.displayhook.set_parent(parent)
  468. self.display_pub.set_parent(parent)
  469. if hasattr(self, '_data_pub'):
  470. self.data_pub.set_parent(parent)
  471. try:
  472. sys.stdout.set_parent(parent)
  473. except AttributeError:
  474. pass
  475. try:
  476. sys.stderr.set_parent(parent)
  477. except AttributeError:
  478. pass
  479. def get_parent(self):
  480. return self.parent_header
  481. def init_magics(self):
  482. super(ZMQInteractiveShell, self).init_magics()
  483. self.register_magics(KernelMagics)
  484. self.magics_manager.register_alias('ed', 'edit')
  485. def init_virtualenv(self):
  486. # Overridden not to do virtualenv detection, because it's probably
  487. # not appropriate in a kernel. To use a kernel in a virtualenv, install
  488. # it inside the virtualenv.
  489. # https://ipython.readthedocs.io/en/latest/install/kernel_install.html
  490. pass
  491. InteractiveShellABC.register(ZMQInteractiveShell)