Debian Codegraph @

jupyter_console/ptshell.py

raw
1 """IPython terminal interface using prompt_toolkit in place of readline"""
2 from __future__ import print_function
3
4 import asyncio
5 import base64
6 import errno
7 from getpass import getpass
8 from io import BytesIO
9 import os
10 from queue import Empty
11 import signal
12 import subprocess
13 import sys
14 from tempfile import TemporaryDirectory
15 import time
16 from warnings import warn
17
18 from typing import Dict as DictType, Any as AnyType
19
20 from zmq import ZMQError
21 from IPython.core import page
22 from traitlets import (
23 Bool,
24 Integer,
25 Float,
26 Unicode,
27 List,
28 Dict,
29 Enum,
30 Instance,
31 Any,
32 )
33 from traitlets.config import SingletonConfigurable
34
35 from .completer import ZMQCompleter
36 from .zmqhistory import ZMQHistoryManager
37 from . import __version__
38
39 # Discriminate version3 for asyncio
40 from prompt_toolkit import __version__ as ptk_version
41 PTK3 = ptk_version.startswith('3.')
42
43 if not PTK3:
44 # use_ayncio_event_loop obsolete in PKT3
45 from prompt_toolkit.eventloop.defaults import use_asyncio_event_loop
46
47 from prompt_toolkit.completion import Completer, Completion
48 from prompt_toolkit.document import Document
49 from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
50 from prompt_toolkit.filters import (
51 Condition,
52 has_focus,
53 has_selection,
54 vi_insert_mode,
55 emacs_insert_mode,
56 is_done,
57 )
58 from prompt_toolkit.history import InMemoryHistory
59 from prompt_toolkit.shortcuts.prompt import PromptSession
60 from prompt_toolkit.shortcuts import print_formatted_text, CompleteStyle
61 from prompt_toolkit.key_binding import KeyBindings
62 from prompt_toolkit.lexers import PygmentsLexer
63 from prompt_toolkit.layout.processors import (
64 ConditionalProcessor,
65 HighlightMatchingBracketProcessor,
66 )
67 from prompt_toolkit.styles import merge_styles
68 from prompt_toolkit.styles.pygments import (style_from_pygments_cls,
69 style_from_pygments_dict)
70 from prompt_toolkit.formatted_text import PygmentsTokens
71 from prompt_toolkit.output import ColorDepth
72 from prompt_toolkit.utils import suspend_to_background_supported
73
74 from pygments.styles import get_style_by_name
75 from pygments.lexers import get_lexer_by_name
76 from pygments.util import ClassNotFound
77 from pygments.token import Token
78
79 from jupyter_console.utils import run_sync, ensure_async
80
81
82 def ask_yes_no(prompt, default=None, interrupt=None):
83 """Asks a question and returns a boolean (y/n) answer.
84
85 If default is given (one of 'y','n'), it is used if the user input is
86 empty. If interrupt is given (one of 'y','n'), it is used if the user
87 presses Ctrl-C. Otherwise the question is repeated until an answer is
88 given.
89
90 An EOF is treated as the default answer. If there is no default, an
91 exception is raised to prevent infinite loops.
92
93 Valid answers are: y/yes/n/no (match is not case sensitive)."""
94
95 answers = {'y': True, 'n': False, 'yes': True, 'no': False}
96 ans = None
97 while ans not in answers.keys():
98 try:
99 ans = input(prompt + ' ').lower()
100 if not ans: # response was an empty string
101 ans = default
102 except KeyboardInterrupt:
103 if interrupt:
104 ans = interrupt
105 except EOFError:
106 if default in answers.keys():
107 ans = default
108 print()
109 else:
110 raise
111
112 return answers[ans]
113
114
115 async def async_input(prompt, loop=None):
116 """Simple async version of input using a the default executor"""
117 if loop is None:
118 loop = asyncio.get_event_loop()
119
120 raw = await loop.run_in_executor(None, input, prompt)
121 return raw
122
123
124 def get_pygments_lexer(name):
125 name = name.lower()
126 if name == 'ipython2':
127 from IPython.lib.lexers import IPythonLexer
128 return IPythonLexer
129 elif name == 'ipython3':
130 from IPython.lib.lexers import IPython3Lexer
131 return IPython3Lexer
132 else:
133 try:
134 return get_lexer_by_name(name).__class__
135 except ClassNotFound:
136 warn("No lexer found for language %r. Treating as plain text." % name)
137 from pygments.lexers.special import TextLexer
138 return TextLexer
139
140
141 class JupyterPTCompleter(Completer):
142 """Adaptor to provide kernel completions to prompt_toolkit"""
143 def __init__(self, jup_completer):
144 self.jup_completer = jup_completer
145
146 def get_completions(self, document, complete_event):
147 if not document.current_line.strip():
148 return
149
150 content = self.jup_completer.complete_request(
151 code=document.text,
152 cursor_pos=document.cursor_position
153 )
154 meta = content["metadata"]
155
156 if "_jupyter_types_experimental" in meta:
157 try:
158 new_meta = {}
159 for c, m in zip(
160 content["matches"], meta["_jupyter_types_experimental"]
161 ):
162 new_meta[c] = m["type"]
163 meta = new_meta
164 except Exception:
165 pass
166
167 start_pos = content["cursor_start"] - document.cursor_position
168 for m in content["matches"]:
169 yield Completion(
170 m,
171 start_position=start_pos,
172 display_meta=meta.get(m, "?"),
173 )
174
175
176 class ZMQTerminalInteractiveShell(SingletonConfigurable):
177 readline_use = False
178
179 pt_cli = None
180
181 _executing = False
182 _execution_state = Unicode('')
183 _pending_clearoutput = False
184 _eventloop = None
185 own_kernel = False # Changed by ZMQTerminalIPythonApp
186
187 editing_mode = Unicode('emacs', config=True,
188 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
189 )
190
191 highlighting_style = Unicode('', config=True,
192 help="The name of a Pygments style to use for syntax highlighting"
193 )
194
195 highlighting_style_overrides = Dict(config=True,
196 help="Override highlighting format for specific tokens"
197 )
198
199 true_color = Bool(False, config=True,
200 help=("Use 24bit colors instead of 256 colors in prompt highlighting. "
201 "If your terminal supports true color, the following command "
202 "should print 'TRUECOLOR' in orange: "
203 "printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"")
204 )
205
206 history_load_length = Integer(1000, config=True,
207 help="How many history items to load into memory"
208 )
209
210 banner = Unicode('Jupyter console {version}\n\n{kernel_banner}', config=True,
211 help=("Text to display before the first prompt. Will be formatted with "
212 "variables {version} and {kernel_banner}.")
213 )
214
215 kernel_timeout = Float(60, config=True,
216 help="""Timeout for giving up on a kernel (in seconds).
217
218 On first connect and restart, the console tests whether the
219 kernel is running and responsive by sending kernel_info_requests.
220 This sets the timeout in seconds for how long the kernel can take
221 before being presumed dead.
222 """
223 )
224
225 image_handler = Enum(('PIL', 'stream', 'tempfile', 'callable'),
226 'PIL', config=True, allow_none=True, help=
227 """
228 Handler for image type output. This is useful, for example,
229 when connecting to the kernel in which pylab inline backend is
230 activated. There are four handlers defined. 'PIL': Use
231 Python Imaging Library to popup image; 'stream': Use an
232 external program to show the image. Image will be fed into
233 the STDIN of the program. You will need to configure
234 `stream_image_handler`; 'tempfile': Use an external program to
235 show the image. Image will be saved in a temporally file and
236 the program is called with the temporally file. You will need
237 to configure `tempfile_image_handler`; 'callable': You can set
238 any Python callable which is called with the image data. You
239 will need to configure `callable_image_handler`.
240 """
241 )
242
243 stream_image_handler = List(config=True, help=
244 """
245 Command to invoke an image viewer program when you are using
246 'stream' image handler. This option is a list of string where
247 the first element is the command itself and reminders are the
248 options for the command. Raw image data is given as STDIN to
249 the program.
250 """
251 )
252
253 tempfile_image_handler = List(config=True, help=
254 """
255 Command to invoke an image viewer program when you are using
256 'tempfile' image handler. This option is a list of string
257 where the first element is the command itself and reminders
258 are the options for the command. You can use {file} and
259 {format} in the string to represent the location of the
260 generated image file and image format.
261 """
262 )
263
264 callable_image_handler = Any(
265 config=True,
266 help="""
267 Callable object called via 'callable' image handler with one
268 argument, `data`, which is `msg["content"]["data"]` where
269 `msg` is the message from iopub channel. For example, you can
270 find base64 encoded PNG data as `data['image/png']`. If your function
271 can't handle the data supplied, it should return `False` to indicate
272 this.
273 """
274 )
275
276 mime_preference = List(
277 default_value=['image/png', 'image/jpeg', 'image/svg+xml'],
278 config=True, help=
279 """
280 Preferred object representation MIME type in order. First
281 matched MIME type will be used.
282 """
283 )
284
285 use_kernel_is_complete = Bool(True, config=True,
286 help="""Whether to use the kernel's is_complete message
287 handling. If False, then the frontend will use its
288 own is_complete handler.
289 """
290 )
291 kernel_is_complete_timeout = Float(1, config=True,
292 help="""Timeout (in seconds) for giving up on a kernel's is_complete
293 response.
294
295 If the kernel does not respond at any point within this time,
296 the kernel will no longer be asked if code is complete, and the
297 console will default to the built-in is_complete test.
298 """
299 )
300
301 # This is configurable on JupyterConsoleApp; this copy is not configurable
302 # to avoid a duplicate config option.
303 confirm_exit = Bool(True,
304 help="""Set to display confirmation dialog on exit.
305 You can always use 'exit' or 'quit', to force a
306 direct exit without any confirmation.
307 """,
308 )
309
310 display_completions = Enum(
311 ("column", "multicolumn", "readlinelike"),
312 help=(
313 "Options for displaying tab completions, 'column', 'multicolumn', and "
314 "'readlinelike'. These options are for `prompt_toolkit`, see "
315 "`prompt_toolkit` documentation for more information."
316 ),
317 default_value="multicolumn",
318 ).tag(config=True)
319
320 prompt_includes_vi_mode = Bool(True,
321 help="Display the current vi mode (when using vi editing mode)."
322 ).tag(config=True)
323
324 highlight_matching_brackets = Bool(True, help="Highlight matching brackets.",).tag(
325 config=True
326 )
327
328 manager = Instance("jupyter_client.KernelManager", allow_none=True)
329 client = Instance("jupyter_client.KernelClient", allow_none=True)
330
331 def _client_changed(self, name, old, new):
332 self.session_id = new.session.session
333 session_id = Unicode()
334
335 def _banner1_default(self):
336 return "Jupyter Console {version}\n".format(version=__version__)
337
338 simple_prompt = Bool(False,
339 help="""Use simple fallback prompt. Features may be limited."""
340 ).tag(config=True)
341
342 def __init__(self, **kwargs):
343 # This is where traits with a config_key argument are updated
344 # from the values on config.
345 super(ZMQTerminalInteractiveShell, self).__init__(**kwargs)
346 self.configurables = [self]
347
348 self.init_history()
349 self.init_completer()
350 self.init_io()
351
352 self.init_kernel_info()
353 self.init_prompt_toolkit_cli()
354 self.keep_running = True
355 self.execution_count = 1
356
357 def init_completer(self):
358 """Initialize the completion machinery.
359
360 This creates completion machinery that can be used by client code,
361 either interactively in-process (typically triggered by the readline
362 library), programmatically (such as in test suites) or out-of-process
363 (typically over the network by remote frontends).
364 """
365 self.Completer = ZMQCompleter(self, self.client, config=self.config)
366
367 def init_history(self):
368 """Sets up the command history. """
369 self.history_manager = ZMQHistoryManager(client=self.client)
370 self.configurables.append(self.history_manager)
371
372 def vi_mode(self):
373 if (getattr(self, 'editing_mode', None) == 'vi'
374 and self.prompt_includes_vi_mode):
375 return '['+str(self.pt_cli.app.vi_state.input_mode)[3:6]+'] '
376 return ''
377
378 def get_prompt_tokens(self, ec=None):
379 if ec is None:
380 ec = self.execution_count
381 return [
382 (Token.Prompt, self.vi_mode()),
383 (Token.Prompt, 'In ['),
384 (Token.PromptNum, str(ec)),
385 (Token.Prompt, ']: '),
386 ]
387
388 def get_continuation_tokens(self, width):
389 return [
390 (Token.Prompt, (" " * (width - 5)) + "...: "),
391 ]
392
393 def get_out_prompt_tokens(self):
394 return [
395 (Token.OutPrompt, 'Out['),
396 (Token.OutPromptNum, str(self.execution_count)),
397 (Token.OutPrompt, ']: ')
398 ]
399
400 def print_out_prompt(self):
401 tokens = self.get_out_prompt_tokens()
402 print_formatted_text(PygmentsTokens(tokens), end='',
403 style = self.pt_cli.app.style)
404
405 def get_remote_prompt_tokens(self):
406 return [
407 (Token.RemotePrompt, self.other_output_prefix),
408 ]
409
410 def print_remote_prompt(self, ec=None):
411 tokens = self.get_remote_prompt_tokens() + self.get_prompt_tokens(ec=ec)
412 print_formatted_text(
413 PygmentsTokens(tokens), end="", style=self.pt_cli.app.style
414 )
415
416 @property
417 def pt_complete_style(self):
418 return {
419 "multicolumn": CompleteStyle.MULTI_COLUMN,
420 "column": CompleteStyle.COLUMN,
421 "readlinelike": CompleteStyle.READLINE_LIKE,
422 }[self.display_completions]
423
424 kernel_info: DictType[str, AnyType] = {}
425
426 def init_kernel_info(self):
427 """Wait for a kernel to be ready, and store kernel info"""
428 timeout = self.kernel_timeout
429 tic = time.time()
430 self.client.hb_channel.unpause()
431 msg_id = self.client.kernel_info()
432 while True:
433 try:
434 reply = self.client.get_shell_msg(timeout=1)
435 except Empty as e:
436 if (time.time() - tic) > timeout:
437 raise RuntimeError("Kernel didn't respond to kernel_info_request") from e
438 else:
439 if reply['parent_header'].get('msg_id') == msg_id:
440 self.kernel_info = reply['content']
441 return
442
443 def show_banner(self):
444 print(self.banner.format(version=__version__,
445 kernel_banner=self.kernel_info.get('banner', '')),end='',flush=True)
446
447 def init_prompt_toolkit_cli(self):
448 if self.simple_prompt or ('JUPYTER_CONSOLE_TEST' in os.environ):
449 # Simple restricted interface for tests so we can find prompts with
450 # pexpect. Multi-line input not supported.
451 async def prompt():
452 prompt = 'In [%d]: ' % self.execution_count
453 raw = await async_input(prompt)
454 return raw
455 self.prompt_for_code = prompt
456 self.print_out_prompt = \
457 lambda: print('Out[%d]: ' % self.execution_count, end='')
458 return
459
460 kb = KeyBindings()
461 insert_mode = vi_insert_mode | emacs_insert_mode
462
463 @kb.add("enter", filter=(has_focus(DEFAULT_BUFFER)
464 & ~has_selection
465 & insert_mode
466 ))
467 def _(event):
468 b = event.current_buffer
469 d = b.document
470 if not (d.on_last_line or d.cursor_position_row >= d.line_count
471 - d.empty_line_count_at_the_end()):
472 b.newline()
473 return
474
475 # Pressing enter flushes any pending display. This also ensures
476 # the displayed execution_count is correct.
477 self.handle_iopub()
478
479 more, indent = self.check_complete(d.text)
480
481 if (not more) and b.accept_handler:
482 b.validate_and_handle()
483 else:
484 b.insert_text('\n' + indent)
485
486 @kb.add("c-c", filter=has_focus(DEFAULT_BUFFER))
487 def _(event):
488 event.current_buffer.reset()
489
490 @kb.add("c-\\", filter=has_focus(DEFAULT_BUFFER))
491 def _(event):
492 raise EOFError
493
494 @kb.add("c-z", filter=Condition(lambda: suspend_to_background_supported()))
495 def _(event):
496 event.cli.suspend_to_background()
497
498 @kb.add("c-o", filter=(has_focus(DEFAULT_BUFFER) & emacs_insert_mode))
499 def _(event):
500 event.current_buffer.insert_text("\n")
501
502 # Pre-populate history from IPython's history database
503 history = InMemoryHistory()
504 last_cell = u""
505 for _, _, cell in self.history_manager.get_tail(self.history_load_length,
506 include_latest=True):
507 # Ignore blank lines and consecutive duplicates
508 cell = cell.rstrip()
509 if cell and (cell != last_cell):
510 history.append_string(cell)
511
512 style_overrides = {
513 Token.Prompt: '#009900',
514 Token.PromptNum: '#00ff00 bold',
515 Token.OutPrompt: '#ff2200',
516 Token.OutPromptNum: '#ff0000 bold',
517 Token.RemotePrompt: '#999900',
518 }
519 if self.highlighting_style:
520 style_cls = get_style_by_name(self.highlighting_style)
521 else:
522 style_cls = get_style_by_name('default')
523 # The default theme needs to be visible on both a dark background
524 # and a light background, because we can't tell what the terminal
525 # looks like. These tweaks to the default theme help with that.
526 style_overrides.update({
527 Token.Number: '#007700',
528 Token.Operator: 'noinherit',
529 Token.String: '#BB6622',
530 Token.Name.Function: '#2080D0',
531 Token.Name.Class: 'bold #2080D0',
532 Token.Name.Namespace: 'bold #2080D0',
533 })
534 style_overrides.update(self.highlighting_style_overrides)
535 style = merge_styles([
536 style_from_pygments_cls(style_cls),
537 style_from_pygments_dict(style_overrides),
538 ])
539
540 editing_mode = getattr(EditingMode, self.editing_mode.upper())
541 langinfo = self.kernel_info.get('language_info', {})
542 lexer = langinfo.get('pygments_lexer', langinfo.get('name', 'text'))
543
544 # If enabled in the settings, highlight matching brackets
545 # when the DEFAULT_BUFFER has the focus
546 input_processors = [ConditionalProcessor(
547 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
548 filter=has_focus(DEFAULT_BUFFER) & ~is_done &
549 Condition(lambda: self.highlight_matching_brackets))
550 ]
551
552 # Tell prompt_toolkit to use the asyncio event loop.
553 # Obsolete in prompt_toolkit.v3
554 if not PTK3:
555 use_asyncio_event_loop()
556
557 self.pt_cli = PromptSession(
558 message=(lambda: PygmentsTokens(self.get_prompt_tokens())),
559 multiline=True,
560 complete_style=self.pt_complete_style,
561 editing_mode=editing_mode,
562 lexer=PygmentsLexer(get_pygments_lexer(lexer)),
563 prompt_continuation=(
564 lambda width, lineno, is_soft_wrap: PygmentsTokens(
565 self.get_continuation_tokens(width)
566 )
567 ),
568 key_bindings=kb,
569 history=history,
570 completer=JupyterPTCompleter(self.Completer),
571 enable_history_search=True,
572 style=style,
573 input_processors=input_processors,
574 color_depth=(ColorDepth.TRUE_COLOR if self.true_color else None),
575 )
576
577 async def prompt_for_code(self):
578 if self.next_input:
579 default = self.next_input
580 self.next_input = None
581 else:
582 default = ''
583
584 if PTK3:
585 text = await self.pt_cli.prompt_async(default=default)
586 else:
587 text = await self.pt_cli.prompt(default=default, async_=True)
588
589 return text
590
591 def init_io(self):
592 if sys.platform not in {'win32', 'cli'}:
593 return
594
595 import colorama
596 colorama.init()
597
598 def check_complete(self, code):
599 if self.use_kernel_is_complete:
600 msg_id = self.client.is_complete(code)
601 try:
602 return self.handle_is_complete_reply(msg_id,
603 timeout=self.kernel_is_complete_timeout)
604 except SyntaxError:
605 return False, ""
606 else:
607 lines = code.splitlines()
608 if len(lines):
609 more = (lines[-1] != "")
610 return more, ""
611 else:
612 return False, ""
613
614 def ask_exit(self):
615 self.keep_running = False
616
617 # This is set from payloads in handle_execute_reply
618 next_input = None
619
620 def pre_prompt(self):
621 if self.next_input:
622 # We can't set the buffer here, because it will be reset just after
623 # this. Adding a callable to pre_run_callables does what we need
624 # after the buffer is reset.
625 s = self.next_input
626
627 def set_doc():
628 self.pt_cli.app.buffer.document = Document(s)
629 if hasattr(self.pt_cli, 'pre_run_callables'):
630 self.pt_cli.app.pre_run_callables.append(set_doc)
631 else:
632 # Older version of prompt_toolkit; it's OK to set the document
633 # directly here.
634 set_doc()
635 self.next_input = None
636
637 async def interact(self, loop=None, display_banner=None):
638 while self.keep_running:
639 print('\n', end='')
640
641 try:
642 code = await self.prompt_for_code()
643 except EOFError:
644 if (not self.confirm_exit) or \
645 ask_yes_no('Do you really want to exit ([y]/n)?', 'y', 'n'):
646 self.ask_exit()
647
648 else:
649 if code:
650 self.run_cell(code, store_history=True)
651
652 async def _main_task(self):
653 loop = asyncio.get_running_loop()
654 tasks = [asyncio.create_task(self.interact(loop=loop))]
655
656 if self.include_other_output:
657 # only poll the iopub channel asynchronously if we
658 # wish to include external content
659 tasks.append(asyncio.create_task(self.handle_external_iopub(loop=loop)))
660
661 _, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
662
663 for task in pending:
664 task.cancel()
665 try:
666 await asyncio.gather(*pending)
667 except asyncio.CancelledError:
668 pass
669
670 def mainloop(self):
671 self.keepkernel = not self.own_kernel
672 # An extra layer of protection in case someone mashing Ctrl-C breaks
673 # out of our internal code.
674 while True:
675 try:
676 asyncio.run(self._main_task())
677 break
678 except KeyboardInterrupt:
679 print("\nKeyboardInterrupt escaped interact()\n")
680
681 if self._eventloop:
682 self._eventloop.close()
683 if self.keepkernel and not self.own_kernel:
684 print('keeping kernel alive')
685 elif self.keepkernel and self.own_kernel:
686 print("owning kernel, cannot keep it alive")
687 self.client.shutdown()
688 else:
689 print("Shutting down kernel")
690 self.client.shutdown()
691
692 def run_cell(self, cell, store_history=True):
693 """Run a complete IPython cell.
694
695 Parameters
696 ----------
697 cell : str
698 The code (including IPython code such as %magic functions) to run.
699 store_history : bool
700 If True, the raw and translated cell will be stored in IPython's
701 history. For user code calling back into IPython's machinery, this
702 should be set to False.
703 """
704 if (not cell) or cell.isspace():
705 # pressing enter flushes any pending display
706 self.handle_iopub()
707 return
708
709 # flush stale replies, which could have been ignored, due to missed heartbeats
710 while run_sync(self.client.shell_channel.msg_ready)():
711 run_sync(self.client.shell_channel.get_msg)()
712 # execute takes 'hidden', which is the inverse of store_hist
713 msg_id = self.client.execute(cell, not store_history)
714
715 # first thing is wait for any side effects (output, stdin, etc.)
716 self._executing = True
717 self._execution_state = "busy"
718 while self._execution_state != 'idle' and self.client.is_alive():
719 try:
720 self.handle_input_request(msg_id, timeout=0.05)
721 except Empty:
722 # display intermediate print statements, etc.
723 self.handle_iopub(msg_id)
724 except ZMQError as e:
725 # Carry on if polling was interrupted by a signal
726 if e.errno != errno.EINTR:
727 raise
728
729 # after all of that is done, wait for the execute reply
730 while self.client.is_alive():
731 try:
732 self.handle_execute_reply(msg_id, timeout=0.05)
733 except Empty:
734 pass
735 else:
736 break
737 self._executing = False
738
739 #-----------------
740 # message handlers
741 #-----------------
742
743 def handle_execute_reply(self, msg_id, timeout=None):
744 kwargs = {"timeout": timeout}
745 msg = run_sync(self.client.shell_channel.get_msg)(**kwargs)
746 if msg["parent_header"].get("msg_id", None) == msg_id:
747
748 self.handle_iopub(msg_id)
749
750 content = msg["content"]
751 status = content['status']
752
753 if status == "aborted":
754 sys.stdout.write("Aborted\n")
755 return
756 elif status == 'ok':
757 # handle payloads
758 for item in content.get("payload", []):
759 source = item['source']
760 if source == 'page':
761 page.page(item['data']['text/plain'])
762 elif source == 'set_next_input':
763 self.next_input = item['text']
764 elif source == 'ask_exit':
765 self.keepkernel = item.get('keepkernel', False)
766 self.ask_exit()
767
768 elif status == 'error':
769 pass
770
771 self.execution_count = int(content["execution_count"] + 1)
772
773 def handle_is_complete_reply(self, msg_id, timeout=None):
774 """
775 Wait for a repsonse from the kernel, and return two values:
776 more? - (boolean) should the frontend ask for more input
777 indent - an indent string to prefix the input
778 Overloaded methods may want to examine the comeplete source. Its is
779 in the self._source_lines_buffered list.
780 """
781 ## Get the is_complete response:
782 msg = None
783 try:
784 kwargs = {"timeout": timeout}
785 msg = run_sync(self.client.shell_channel.get_msg)(**kwargs)
786 except Empty:
787 warn('The kernel did not respond to an is_complete_request. '
788 'Setting `use_kernel_is_complete` to False.')
789 self.use_kernel_is_complete = False
790 return False, ""
791 ## Handle response:
792 if msg["parent_header"].get("msg_id", None) != msg_id:
793 warn('The kernel did not respond properly to an is_complete_request: %s.' % str(msg))
794 return False, ""
795 else:
796 status = msg["content"].get("status", None)
797 indent = msg["content"].get("indent", "")
798 ## Return more? and indent string
799 if status == "complete":
800 return False, indent
801 elif status == "incomplete":
802 return True, indent
803 elif status == "invalid":
804 raise SyntaxError()
805 elif status == "unknown":
806 return False, indent
807 else:
808 warn('The kernel sent an invalid is_complete_reply status: "%s".' % status)
809 return False, indent
810
811 include_other_output = Bool(False, config=True,
812 help="""Whether to include output from clients
813 other than this one sharing the same kernel.
814 """
815 )
816 other_output_prefix = Unicode("Remote ", config=True,
817 help="""Prefix to add to outputs coming from clients other than this one.
818
819 Only relevant if include_other_output is True.
820 """
821 )
822
823 def from_here(self, msg):
824 """Return whether a message is from this session"""
825 return msg['parent_header'].get("session", self.session_id) == self.session_id
826
827 def include_output(self, msg):
828 """Return whether we should include a given output message"""
829 from_here = self.from_here(msg)
830 if msg['msg_type'] == 'execute_input':
831 # only echo inputs not from here
832 return self.include_other_output and not from_here
833
834 if self.include_other_output:
835 return True
836 else:
837 return from_here
838
839 async def handle_external_iopub(self, loop=None):
840 while self.keep_running:
841 # we need to check for keep_running from time to time
842 poll_result = await ensure_async(self.client.iopub_channel.socket.poll(0))
843 if poll_result:
844 self.handle_iopub()
845 await asyncio.sleep(0.5)
846
847 def handle_iopub(self, msg_id=''):
848 """Process messages on the IOPub channel
849
850 This method consumes and processes messages on the IOPub channel,
851 such as stdout, stderr, execute_result and status.
852
853 It only displays output that is caused by this session.
854 """
855 while run_sync(self.client.iopub_channel.msg_ready)():
856 sub_msg = run_sync(self.client.iopub_channel.get_msg)()
857 msg_type = sub_msg['header']['msg_type']
858
859 # Update execution_count in case it changed in another session
860 if msg_type == "execute_input":
861 self.execution_count = int(sub_msg["content"]["execution_count"]) + 1
862
863 if self.include_output(sub_msg):
864 if msg_type == 'status':
865 self._execution_state = sub_msg["content"]["execution_state"]
866
867 elif msg_type == 'stream':
868 if sub_msg["content"]["name"] == "stdout":
869 if self._pending_clearoutput:
870 print("\r", end="")
871 self._pending_clearoutput = False
872 print(sub_msg["content"]["text"], end="")
873 sys.stdout.flush()
874 elif sub_msg["content"]["name"] == "stderr":
875 if self._pending_clearoutput:
876 print("\r", file=sys.stderr, end="")
877 self._pending_clearoutput = False
878 print(sub_msg["content"]["text"], file=sys.stderr, end="")
879 sys.stderr.flush()
880
881 elif msg_type == 'execute_result':
882 if self._pending_clearoutput:
883 print("\r", end="")
884 self._pending_clearoutput = False
885 self.execution_count = int(sub_msg["content"]["execution_count"])
886 if not self.from_here(sub_msg):
887 sys.stdout.write(self.other_output_prefix)
888 format_dict = sub_msg["content"]["data"]
889 self.handle_rich_data(format_dict)
890
891 if 'text/plain' not in format_dict:
892 continue
893
894 # prompt_toolkit writes the prompt at a slightly lower level,
895 # so flush streams first to ensure correct ordering.
896 sys.stdout.flush()
897 sys.stderr.flush()
898 self.print_out_prompt()
899 text_repr = format_dict['text/plain']
900 if '\n' in text_repr:
901 # For multi-line results, start a new line after prompt
902 print()
903 print(text_repr)
904
905 # Remote: add new prompt
906 if not self.from_here(sub_msg):
907 sys.stdout.write('\n')
908 sys.stdout.flush()
909 self.print_remote_prompt()
910
911 elif msg_type == 'display_data':
912 data = sub_msg["content"]["data"]
913 handled = self.handle_rich_data(data)
914 if not handled:
915 if not self.from_here(sub_msg):
916 sys.stdout.write(self.other_output_prefix)
917 # if it was an image, we handled it by now
918 if 'text/plain' in data:
919 print(data['text/plain'])
920
921 # If execute input: print it
922 elif msg_type == 'execute_input':
923 content = sub_msg['content']
924 ec = content.get('execution_count', self.execution_count - 1)
925
926 # New line
927 sys.stdout.write('\n')
928 sys.stdout.flush()
929
930 # With `Remote In [3]: `
931 self.print_remote_prompt(ec=ec)
932
933 # And the code
934 sys.stdout.write(content['code'] + '\n')
935
936 elif msg_type == 'clear_output':
937 if sub_msg["content"]["wait"]:
938 self._pending_clearoutput = True
939 else:
940 print("\r", end="")
941
942 elif msg_type == 'error':
943 for frame in sub_msg["content"]["traceback"]:
944 print(frame, file=sys.stderr)
945
946 _imagemime = {
947 'image/png': 'png',
948 'image/jpeg': 'jpeg',
949 'image/svg+xml': 'svg',
950 }
951
952 def handle_rich_data(self, data):
953 for mime in self.mime_preference:
954 if mime in data and mime in self._imagemime:
955 if self.handle_image(data, mime):
956 return True
957 return False
958
959 def handle_image(self, data, mime):
960 handler = getattr(
961 self, 'handle_image_{0}'.format(self.image_handler), None)
962 if handler:
963 return handler(data, mime)
964
965 def handle_image_PIL(self, data, mime):
966 if mime not in ('image/png', 'image/jpeg'):
967 return False
968 try:
969 from PIL import Image, ImageShow
970 except ImportError:
971 return False
972 raw = base64.decodebytes(data[mime].encode('ascii'))
973 img = Image.open(BytesIO(raw))
974 return ImageShow.show(img)
975
976 def handle_image_stream(self, data, mime):
977 raw = base64.decodebytes(data[mime].encode('ascii'))
978 imageformat = self._imagemime[mime]
979 fmt = dict(format=imageformat)
980 args = [s.format(**fmt) for s in self.stream_image_handler]
981 with subprocess.Popen(args, stdin=subprocess.PIPE,
982 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) as proc:
983 proc.communicate(raw)
984 return (proc.returncode == 0)
985
986 def handle_image_tempfile(self, data, mime):
987 raw = base64.decodebytes(data[mime].encode('ascii'))
988 imageformat = self._imagemime[mime]
989 filename = 'tmp.{0}'.format(imageformat)
990 with TemporaryDirectory() as tempdir:
991 fullpath = os.path.join(tempdir, filename)
992 with open(fullpath, 'wb') as f:
993 f.write(raw)
994 fmt = dict(file=fullpath, format=imageformat)
995 args = [s.format(**fmt) for s in self.tempfile_image_handler]
996 rc = subprocess.call(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
997 return (rc == 0)
998
999 def handle_image_callable(self, data, mime):
1000 res = self.callable_image_handler(data)
1001 if res is not False:
1002 # If handler func returns e.g. None, assume it has handled the data.
1003 res = True
1004 return res
1005
1006 def handle_input_request(self, msg_id, timeout=0.1):
1007 """ Method to capture raw_input
1008 """
1009 req = run_sync(self.client.stdin_channel.get_msg)(timeout=timeout)
1010 # in case any iopub came while we were waiting:
1011 self.handle_iopub(msg_id)
1012 if msg_id == req["parent_header"].get("msg_id"):
1013 # wrap SIGINT handler
1014 real_handler = signal.getsignal(signal.SIGINT)
1015
1016 def double_int(sig, frame):
1017 # call real handler (forwards sigint to kernel),
1018 # then raise local interrupt, stopping local raw_input
1019 real_handler(sig, frame)
1020 raise KeyboardInterrupt
1021 signal.signal(signal.SIGINT, double_int)
1022 content = req['content']
1023 read = getpass if content.get('password', False) else input
1024 try:
1025 raw_data = read(content["prompt"])
1026 except EOFError:
1027 # turn EOFError into EOF character
1028 raw_data = '\x04'
1029 except KeyboardInterrupt:
1030 sys.stdout.write('\n')
1031 return
1032 finally:
1033 # restore SIGINT handler
1034 signal.signal(signal.SIGINT, real_handler)
1035
1036 # only send stdin reply if there *was not* another request
1037 # or execution finished while we were reading.
1038 if not (run_sync(self.client.stdin_channel.msg_ready)() or
1039 run_sync(self.client.shell_channel.msg_ready)()):
1040 self.client.input(raw_data)