-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
shell.py
1457 lines (1234 loc) · 50.4 KB
/
shell.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Shell Widget for the IPython Console
"""
# Standard library imports
import os
import os.path as osp
import time
from textwrap import dedent
# Third party imports
from qtpy.QtCore import Qt, Signal, Slot
from qtpy.QtGui import QClipboard, QTextCursor, QTextFormat
from qtpy.QtWidgets import QApplication, QMessageBox
from traitlets import observe
# Local imports
from spyder.api.plugins import Plugins
from spyder.api.widgets.mixins import SpyderWidgetMixin
from spyder.config.base import _, is_conda_based_app, running_under_pytest
from spyder.config.gui import get_color_scheme, is_dark_interface
from spyder.plugins.ipythonconsole.api import (
IPythonConsoleWidgetCornerWidgets,
IPythonConsoleWidgetMenus,
ClientContextMenuActions,
ClientContextMenuSections
)
from spyder.plugins.ipythonconsole.utils.style import (
create_qss_style, create_style_class)
from spyder.plugins.ipythonconsole.utils.kernel_handler import (
KernelConnectionState)
from spyder.plugins.ipythonconsole.widgets import (
ControlWidget, DebuggingWidget, FigureBrowserWidget, HelpWidget,
NamepaceBrowserWidget, PageControlWidget)
from spyder.utils import syntaxhighlighters as sh
from spyder.utils.palette import SpyderPalette
from spyder.utils.clipboard_helper import CLIPBOARD_HELPER
from spyder.widgets.helperwidgets import MessageCheckBox
MODULES_FAQ_URL = (
"https://docs.spyder-ide.org/5/faq.html#using-packages-installer")
class ShellWidget(NamepaceBrowserWidget, HelpWidget, DebuggingWidget,
FigureBrowserWidget, SpyderWidgetMixin):
"""
Shell widget for the IPython Console
This is the widget in charge of executing code
"""
PLUGIN_NAME = Plugins.IPythonConsole
# NOTE: Signals can't be assigned separately to each widget
# That's why we define all needed signals here.
# For NamepaceBrowserWidget
sig_show_syspath = Signal(object)
sig_show_env = Signal(object)
# For FigureBrowserWidget
sig_new_inline_figure = Signal(object, str)
# For DebuggingWidget
sig_pdb_step = Signal(str, int)
"""
This signal is emitted when Pdb reaches a new line.
Parameters
----------
filename: str
The filename the debugger stepped in.
line_number: int
The line number the debugger stepped in.
"""
sig_pdb_stack = Signal(object, int)
"""
This signal is emitted when the Pdb stack changed.
Parameters
----------
pdb_stack: traceback.StackSummary
The current pdb stack.
pdb_index: int
The index in the stack.
"""
sig_pdb_state_changed = Signal(bool)
"""
This signal is emitted every time a Pdb interaction happens.
Parameters
----------
pdb_state: bool
Whether the debugger is waiting for input.
"""
sig_pdb_prompt_ready = Signal()
"""Called when pdb request new input"""
# For ShellWidget
sig_focus_changed = Signal()
sig_new_client = Signal()
# Kernel died and restarted (not user requested)
sig_prompt_ready = Signal()
sig_remote_execute = Signal()
# For global working directory
sig_working_directory_changed = Signal(str)
# For printing internal errors
sig_exception_occurred = Signal(dict)
# To save values and messages returned by the kernel
_kernel_is_starting = True
# Request plugins to send additional configuration to the Spyder kernel
sig_config_spyder_kernel = Signal()
# To notify of kernel connection, disconnection and kernel errors
sig_shellwidget_created = Signal(object)
sig_shellwidget_deleted = Signal(object)
sig_shellwidget_errored = Signal(object)
# To request restart
sig_restart_kernel = Signal()
sig_kernel_state_arrived = Signal(dict)
"""
A new kernel state, which needs to be processed.
Parameters
----------
state: dict
Kernel state. The structure of this dictionary is defined in the
`SpyderKernel.get_state` method of Spyder-kernels.
"""
def __init__(self, ipyclient, additional_options, interpreter_versions,
handlers, *args, special_kernel=None, **kw):
# To override the Qt widget used by RichJupyterWidget
self.custom_control = ControlWidget
self.custom_page_control = PageControlWidget
self.custom_edit = True
super(ShellWidget, self).__init__(*args, **kw)
self.ipyclient = ipyclient
self.additional_options = additional_options
self.interpreter_versions = interpreter_versions
self.special_kernel = special_kernel
# Keyboard shortcuts
# Registered here to use shellwidget as the parent
self.shortcuts = self.create_shortcuts()
# Set the color of the matched parentheses here since the qtconsole
# uses a hard-coded value that is not modified when the color scheme is
# set in the qtconsole constructor. See spyder-ide/spyder#4806.
self.set_bracket_matcher_color_scheme(self.syntax_style)
self.shutting_down = False
self.kernel_manager = None
self.kernel_client = None
self.kernel_handler = None
self._kernel_configuration = {}
self.is_kernel_configured = False
self._init_kernel_setup = False
if handlers is None:
handlers = {}
else:
# Avoid changing the plugin dict
handlers = handlers.copy()
handlers.update({
'show_pdb_output': self.show_pdb_output,
'pdb_input': self.pdb_input,
'update_state': self.update_state,
})
self.kernel_comm_handlers = handlers
self._execute_queue = []
self.executed.connect(self.pop_execute_queue)
# Show a message in our installers to explain users how to use
# modules that don't come with them.
self.show_modules_message = is_conda_based_app()
# The Qtconsole shortcuts for the actions below don't work in Spyder,
# so we disable them.
self._copy_raw_action.setShortcut('')
self.export_action.setShortcut('')
self.select_all_action.setShortcut('')
self.print_action.setShortcut('')
# ---- Public API
@property
def is_spyder_kernel(self):
if self.kernel_handler is None:
return False
return self.kernel_handler.known_spyder_kernel
@property
def spyder_kernel_ready(self):
"""
Check if Spyder kernel is ready.
Notes
-----
This is used for our tests.
"""
if self.kernel_handler is None:
return False
return (
self.kernel_handler.connection_state ==
KernelConnectionState.SpyderKernelReady)
def connect_kernel(self, kernel_handler, first_connect=True):
"""Connect to the kernel using our handler."""
# Kernel client
kernel_client = kernel_handler.kernel_client
kernel_client.stopped_channels.connect(self.notify_deleted)
self.kernel_client = kernel_client
self.kernel_manager = kernel_handler.kernel_manager
self.kernel_handler = kernel_handler
# Register handlers declared here before emitting sig_kernel_is_ready
# so that handlers declared elsewhere can't be called first, which can
# generate errors.
for request_id, handler in self.kernel_comm_handlers.items():
self.kernel_handler.kernel_comm.register_call_handler(
request_id, handler
)
if first_connect:
# Let plugins know that a new kernel is connected
self.sig_shellwidget_created.emit(self)
else:
# Set _starting to False to avoid reset at first prompt
self._starting = False
# Connect signals
kernel_handler.sig_kernel_is_ready.connect(
self.handle_kernel_is_ready)
kernel_handler.sig_kernel_connection_error.connect(
self.handle_kernel_connection_error)
kernel_handler.connect_()
def disconnect_kernel(self, shutdown_kernel=True, will_reconnect=True):
"""
Disconnect from current kernel.
Parameters:
-----------
shutdown_kernel: bool
If True, the kernel is shut down.
will_reconnect: bool
If False, emits `sig_shellwidget_deleted` so the plugins can close
related widgets.
"""
kernel_handler = self.kernel_handler
if not kernel_handler:
return
kernel_client = kernel_handler.kernel_client
kernel_handler.sig_kernel_is_ready.disconnect(
self.handle_kernel_is_ready)
kernel_handler.sig_kernel_connection_error.disconnect(
self.handle_kernel_connection_error)
kernel_handler.kernel_client.stopped_channels.disconnect(
self.notify_deleted)
if self._init_kernel_setup:
self._init_kernel_setup = False
kernel_handler.kernel_comm.sig_exception_occurred.disconnect(
self.sig_exception_occurred)
kernel_client.control_channel.message_received.disconnect(
self._dispatch)
kernel_handler.close(shutdown_kernel)
if not will_reconnect:
self.notify_deleted()
# Reset state
self.reset_kernel_state()
self.kernel_client = None
self.kernel_manager = None
self.kernel_handler = None
def handle_kernel_is_ready(self):
"""The kernel is ready"""
if (
self.kernel_handler.connection_state ==
KernelConnectionState.SpyderKernelReady
):
self.setup_spyder_kernel()
def handle_kernel_connection_error(self):
"""An error occurred when connecting to the kernel."""
if self.kernel_handler.connection_state == KernelConnectionState.Error:
# A wrong version is connected
self.ipyclient.show_kernel_error(
self.kernel_handler.kernel_error_message,
)
def notify_deleted(self):
"""Notify that the shellwidget was deleted."""
self.sig_shellwidget_deleted.emit(self)
def shutdown(self, shutdown_kernel=True):
"""Shutdown connection and kernel."""
if self.shutting_down:
return
self.shutting_down = True
if self.kernel_handler is not None:
self.kernel_handler.close(shutdown_kernel)
super().shutdown()
def reset_kernel_state(self):
"""Reset the kernel state."""
self._prompt_requested = False
self._pdb_recursion_level = 0
self._reading = False
def call_kernel(self, interrupt=False, blocking=False, callback=None,
timeout=None, display_error=False):
"""
Send message to Spyder kernel connected to this console.
Parameters
----------
interrupt: bool
Interrupt the kernel while running or in Pdb to perform
the call.
blocking: bool
Make a blocking call, i.e. wait on this side until the
kernel sends its response.
callback: callable
Callable to process the response sent from the kernel
on the Spyder side.
timeout: int or None
Maximum time (in seconds) before giving up when making a
blocking call to the kernel. If None, a default timeout
(defined in commbase.py, present in spyder-kernels) is
used.
display_error: bool
If an error occurs, should it be printed to the console.
"""
return self.kernel_handler.kernel_comm.remote_call(
interrupt=interrupt,
blocking=blocking,
callback=callback,
timeout=timeout,
display_error=display_error
)
@property
def is_external_kernel(self):
"""Check if this is an external kernel."""
return self.kernel_manager is None
def setup_spyder_kernel(self):
"""Setup spyder kernel"""
if not self._init_kernel_setup:
# Only do this setup once
self._init_kernel_setup = True
# For errors
self.kernel_handler.kernel_comm.sig_exception_occurred.connect(
self.sig_exception_occurred)
# For completions
self.kernel_client.control_channel.message_received.connect(
self._dispatch)
# Redefine the complete method to work while debugging.
self._redefine_complete_for_dbg(self.kernel_client)
# Setup to do after restart
# Check for fault and send config
self.kernel_handler.poll_fault_text()
self.send_spyder_kernel_configuration()
run_lines = self.get_conf('startup/run_lines')
if run_lines:
self.execute(run_lines, hidden=True)
if self.get_conf('startup/use_run_file'):
run_file = self.get_conf('startup/run_file')
if run_file:
self.call_kernel().safe_exec(run_file)
def send_spyder_kernel_configuration(self):
"""Send kernel configuration to spyder kernel."""
self.is_kernel_configured = False
# Set matplotlib backend
self.send_mpl_backend()
# set special kernel
self.set_special_kernel()
# Set current cwd
self.set_cwd()
# To apply style
self.set_color_scheme(self.syntax_style, reset=False)
# Enable faulthandler
self.set_kernel_configuration("faulthandler", True)
# Give a chance to plugins to configure the kernel
self.sig_config_spyder_kernel.emit()
if self.is_external_kernel:
# Enable wurlitzer
# Not necessary if started by spyder
# Does not work if the external kernel is on windows
self.set_kernel_configuration("wurlitzer", True)
if self.get_conf('autoreload'):
# Enable autoreload_magic
self.set_kernel_configuration("autoreload_magic", True)
self.call_kernel(
interrupt=self.is_debugging(),
callback=self.kernel_configure_callback
).set_configuration(self._kernel_configuration)
self.is_kernel_configured = True
def set_kernel_configuration(self, key, value):
"""Set kernel configuration."""
if self.is_kernel_configured:
if (
key not in self._kernel_configuration
or self._kernel_configuration[key] != value
):
# Do not send twice
self.call_kernel(
interrupt=self.is_debugging(),
callback=self.kernel_configure_callback
).set_configuration({key: value})
self._kernel_configuration[key] = value
def kernel_configure_callback(self, dic):
"""Kernel configuration callback"""
for key, value in dic.items():
if key == "faulthandler":
self.kernel_handler.faulthandler_setup(value)
elif key == "special_kernel_error":
self.ipyclient._show_special_console_error(value)
def pop_execute_queue(self):
"""Pop one waiting instruction."""
if self._execute_queue:
self.execute(*self._execute_queue.pop(0))
def interrupt_kernel(self):
"""Attempts to interrupt the running kernel."""
# Empty queue when interrupting
# Fixes spyder-ide/spyder#7293.
self._execute_queue = []
if self.spyder_kernel_ready:
self._reading = False
# Check if there is a kernel that can be interrupted before trying
# to do it.
# Fixes spyder-ide/spyder#20212
if self.kernel_manager and self.kernel_manager.has_kernel:
self.call_kernel(interrupt=True).raise_interrupt_signal()
elif self.ipyclient.server_id:
# Request an interrupt to the server for remote kernels
self.ipyclient.sig_interrupt_kernel_requested.emit(
self.ipyclient.server_id, self.ipyclient.kernel_id
)
else:
self._append_html(
_("<br><br>The kernel appears to be dead, so it can't be "
"interrupted. Please open a new console to keep "
"working.<br>")
)
else:
self._append_html(
_("<br><br>It is not possible to interrupt a non-Spyder "
"kernel I did not start.<br>")
)
def execute(self, source=None, hidden=False, interactive=False):
"""
Executes source or the input buffer, possibly prompting for more
input.
"""
# Needed for cases where there is no kernel initialized but
# an execution is triggered like when setting initial configs.
# See spyder-ide/spyder#16896
if self.kernel_client is None:
return
if self._executing:
self._execute_queue.append((source, hidden, interactive))
return
super(ShellWidget, self).execute(source, hidden, interactive)
def is_running(self):
"""Check if shell is running."""
return (
self.kernel_client is not None and
self.kernel_client.channels_running
)
def set_cwd(self, dirname=None, emit_cwd_change=False):
"""
Set shell current working directory.
Parameters
----------
dirname: str
Path to the new current working directory.
emit_cwd_change: bool
Whether to emit a Qt signal that informs other panes in Spyder that
the current working directory has changed.
"""
if self.ipyclient.hostname is not None:
# Only sync for local kernels
return
if dirname is None:
if not self.get_cwd():
return
dirname = self.get_cwd()
elif os.name == 'nt':
# Use normpath instead of replacing '\' with '\\'
# See spyder-ide/spyder#10785
dirname = osp.normpath(dirname)
self.set_kernel_configuration("cwd", dirname)
if emit_cwd_change:
self.sig_working_directory_changed.emit(dirname)
def send_mpl_backend(self, option=None):
"""
Send matplotlib backend.
If `option` is not None only send the related options.
"""
if not self.spyder_kernel_ready:
# will be sent later
return
# Set Matplotlib backend with Spyder options
pylab_n = 'pylab'
pylab_o = self.get_conf(pylab_n)
if option is not None and not pylab_o:
# The options are only related to pylab_o
# So no need to change the backend
return
pylab_autoload_n = 'pylab/autoload'
pylab_backend_n = 'pylab/backend'
figure_format_n = 'pylab/inline/figure_format'
resolution_n = 'pylab/inline/resolution'
width_n = 'pylab/inline/width'
height_n = 'pylab/inline/height'
fontsize_n = 'pylab/inline/fontsize'
bottom_n = 'pylab/inline/bottom'
bbox_inches_n = 'pylab/inline/bbox_inches'
backend_o = self.get_conf(pylab_backend_n)
inline_backend = 'inline'
matplotlib_conf = {}
if pylab_o:
# Figure format
format_o = self.get_conf(figure_format_n)
if format_o and (option is None or figure_format_n in option):
matplotlib_conf[figure_format_n] = format_o
# Resolution
resolution_o = self.get_conf(resolution_n)
if resolution_o is not None and (
option is None or resolution_n in option):
matplotlib_conf[resolution_n] = resolution_o
# Figure size
width_o = float(self.get_conf(width_n))
height_o = float(self.get_conf(height_n))
if option is None or (width_n in option or height_n in option):
if width_o is not None:
matplotlib_conf[width_n] = width_o
if height_o is not None:
matplotlib_conf[height_n] = height_o
# Font size
fontsize_o = float(self.get_conf(fontsize_n))
if (
fontsize_o is not None
and (option is None or fontsize_n in option)
):
matplotlib_conf[fontsize_n] = fontsize_o
# Bottom part
bottom_o = float(self.get_conf(bottom_n))
if (
bottom_o is not None
and (option is None or bottom_n in option)
):
matplotlib_conf[bottom_n] = bottom_o
# Print figure kwargs
bbox_inches_o = self.get_conf(bbox_inches_n)
if option is None or bbox_inches_n in option:
matplotlib_conf[bbox_inches_n] = bbox_inches_o
if pylab_o and backend_o is not None:
mpl_backend = backend_o
else:
# Set Matplotlib backend to inline for external kernels.
# Fixes issue spyder-ide/spyder-kernels#108
mpl_backend = inline_backend
# Automatically load Pylab and Numpy, or only set Matplotlib
# backend
autoload_pylab_o = self.get_conf(pylab_autoload_n)
if option is None or pylab_backend_n in option:
matplotlib_conf[pylab_backend_n] = mpl_backend
if option is None or pylab_autoload_n in option:
matplotlib_conf[pylab_autoload_n] = autoload_pylab_o
if matplotlib_conf and pylab_o:
self.set_kernel_configuration("matplotlib", matplotlib_conf)
def get_cwd(self):
"""
Get current working directory.
Notes
-----
* This doesn't ask the kernel for its working directory. Instead, it
returns the last value of it saved here.
* We do it for performance reasons because we call this method when
switching consoles to update the Working Directory toolbar.
"""
return self._kernel_configuration.get("cwd", '')
def update_state(self, state):
"""
New state received from kernel.
"""
cwd = state.pop("cwd", None)
if cwd and self.get_cwd() and cwd != self.get_cwd():
# Only set it if self.get_cwd() is already set
self._kernel_configuration["cwd"] = cwd
self.sig_working_directory_changed.emit(cwd)
if state:
self.sig_kernel_state_arrived.emit(state)
def set_bracket_matcher_color_scheme(self, color_scheme):
"""Set color scheme for matched parentheses."""
bsh = sh.BaseSH(parent=self, color_scheme=color_scheme)
mpcolor = bsh.get_matched_p_color()
self._bracket_matcher.format.setBackground(mpcolor)
def set_color_scheme(self, color_scheme, reset=True):
"""Set color scheme of the shell."""
self.set_bracket_matcher_color_scheme(color_scheme)
self.style_sheet, dark_color = create_qss_style(color_scheme)
self.syntax_style = color_scheme
self._style_sheet_changed()
self._syntax_style_changed()
if reset:
self.reset(clear=True)
if not self.spyder_kernel_ready:
# Will be sent later
return
self.set_kernel_configuration(
"color scheme", "dark" if not dark_color else "light"
)
def update_syspath(self, path_dict, new_path_dict):
"""Update sys.path contents on kernel."""
self.call_kernel(
interrupt=True,
blocking=False).update_syspath(path_dict, new_path_dict)
def request_syspath(self):
"""Ask the kernel for sys.path contents."""
self.call_kernel(
interrupt=True, callback=self.sig_show_syspath.emit).get_syspath()
def request_env(self):
"""Ask the kernel for environment variables."""
self.call_kernel(
interrupt=True, callback=self.sig_show_env.emit).get_env()
def set_show_calltips(self, show_calltips):
"""Enable/Disable showing calltips."""
self.enable_calltips = show_calltips
def set_buffer_size(self, buffer_size):
"""Set buffer size for the shell."""
self.buffer_size = buffer_size
def set_completion_type(self, completion_type):
"""Set completion type (Graphical, Terminal, Plain) for the shell."""
self.gui_completion = completion_type
def set_in_prompt(self, in_prompt):
"""Set appereance of the In prompt."""
self.in_prompt = in_prompt
def set_out_prompt(self, out_prompt):
"""Set appereance of the Out prompt."""
self.out_prompt = out_prompt
def get_matplotlib_backend(self):
"""Call kernel to get current backend."""
return self.call_kernel(
interrupt=True,
blocking=True).get_matplotlib_backend()
def get_mpl_interactive_backend(self):
"""Call kernel to get current interactive backend."""
return self.call_kernel(
interrupt=True,
blocking=True).get_mpl_interactive_backend()
def set_jedi_completer(self, use_jedi):
"""Set if jedi completions should be used."""
self.set_kernel_configuration(
"jedi_completer", use_jedi
)
def set_greedy_completer(self, use_greedy):
"""Set if greedy completions should be used."""
self.set_kernel_configuration(
"greedy_completer", use_greedy
)
def set_autocall(self, autocall):
"""Set if autocall functionality is enabled or not."""
self.set_kernel_configuration(
"autocall", autocall
)
# --- To handle the banner
def long_banner(self):
"""Banner for clients with additional content."""
# Default banner
py_ver = self.interpreter_versions['python_version'].split('\n')[0]
ipy_ver = self.interpreter_versions['ipython_version']
banner_parts = [
'Python %s\n' % py_ver,
'Type "copyright", "credits" or "license" for more information.',
'\n\n',
]
if ipy_ver:
banner_parts.append(
'IPython %s -- An enhanced Interactive Python.\n' % ipy_ver
)
else:
banner_parts.append('IPython -- An enhanced Interactive Python.\n')
banner = ''.join(banner_parts)
# Pylab additions
pylab_o = self.additional_options['pylab']
autoload_pylab_o = self.additional_options['autoload_pylab']
if pylab_o and autoload_pylab_o:
pylab_message = ("\nPopulating the interactive namespace from "
"numpy and matplotlib\n")
banner = banner + pylab_message
# Sympy additions
sympy_o = self.additional_options['sympy']
if sympy_o:
lines = """
These commands were executed:
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
"""
banner = banner + lines
if (pylab_o and sympy_o):
lines = """
Warning: pylab (numpy and matplotlib) and symbolic math (sympy) are both
enabled at the same time. Some pylab functions are going to be overrided by
the sympy module (e.g. plot)
"""
banner = banner + lines
return banner
def short_banner(self):
"""Short banner with Python and IPython versions only."""
py_ver = self.interpreter_versions['python_version'].split(' ')[0]
ipy_ver = self.interpreter_versions['ipython_version']
banner = 'Python %s -- IPython %s' % (py_ver, ipy_ver)
return banner
# --- To define additional shortcuts
def clear_console(self):
self.execute("%clear")
# Stop reading as any input has been removed.
self._reading = False
@Slot()
def _reset_namespace(self):
warning = self.get_conf('show_reset_namespace_warning')
self.reset_namespace(warning=warning)
def reset_namespace(self, warning=False, message=False):
"""Reset the namespace by removing all names defined by the user."""
# Don't show the warning when running our tests.
if running_under_pytest():
warning = False
if warning:
reset_str = _("Remove all variables")
warn_str = _("All user-defined variables will be removed. "
"Are you sure you want to proceed?")
box = MessageCheckBox(icon=QMessageBox.Warning, parent=self)
box.setWindowTitle(reset_str)
box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
box.setDefaultButton(QMessageBox.Yes)
box.set_checkbox_text(_("Don't show again."))
box.set_checked(False)
box.set_check_visible(True)
box.setText(warn_str)
box.buttonClicked.connect(
lambda button: self.handle_reset_message_answer(
box, button, message)
)
box.show()
else:
self._perform_reset(message)
def handle_reset_message_answer(self, message_box, button, message):
"""
Handle the answer of the reset namespace message box.
Parameters
----------
message_box
Instance of the message box shown to the user.
button: QPushButton
Instance of the button clicked by the user on the dialog.
message: bool
Whether to show a message in the console telling users the
namespace was reset.
"""
if message_box.buttonRole(button) == QMessageBox.YesRole:
self._update_reset_options(message_box)
self._perform_reset(message)
else:
self._update_reset_options(message_box)
def _perform_reset(self, message):
"""
Perform the reset namespace operation.
Parameters
----------
message: bool
Whether to show a message in the console telling users the
namespace was reset.
"""
try:
if self.is_waiting_pdb_input():
self.execute('%reset -f')
else:
if message:
self.reset()
self._append_html(
_("<br><br>Removing all variables...<br>"),
before_prompt=False
)
self.insert_horizontal_ruler()
self.silent_execute("%reset -f")
self.set_special_kernel()
if self.spyder_kernel_ready:
self.call_kernel().close_all_mpl_figures()
self.send_spyder_kernel_configuration()
except AttributeError:
pass
def set_special_kernel(self):
"""Reset special kernel"""
if not self.special_kernel:
return
# Check if the dependecies for special consoles are available.
self.set_kernel_configuration(
"special_kernel", self.special_kernel
)
def _update_reset_options(self, message_box):
"""
Update options and variables based on the interaction in the
reset warning message box shown to the user.
"""
self.set_conf(
'show_reset_namespace_warning',
not message_box.is_checked()
)
self.ipyclient.reset_warning = not message_box.is_checked()
def create_shortcuts(self):
"""Create shortcuts for ipyconsole."""
inspect = self.config_shortcut(
self._control.inspect_current_object,
context='ipython_console',
name='Inspect current object',
parent=self)
clear_console = self.config_shortcut(
self.clear_console,
context='ipython_console',
name='Clear shell',
parent=self)
restart_kernel = self.config_shortcut(
self.sig_restart_kernel,
context='ipython_console',
name='Restart kernel',
parent=self)
new_tab = self.config_shortcut(
self.sig_new_client,
context='ipython_console',
name='new tab',
parent=self)
reset_namespace = self.config_shortcut(
self._reset_namespace,
context='ipython_console',
name='reset namespace',
parent=self)
array_inline = self.config_shortcut(
self._control.enter_array_inline,
context='ipython_console',
name='enter array inline',
parent=self)
array_table = self.config_shortcut(
self._control.enter_array_table,
context='ipython_console',
name='enter array table',
parent=self)
clear_line = self.config_shortcut(
self.ipyclient.clear_line,
context='ipython_console',
name='clear line',
parent=self)
return [inspect, clear_console, restart_kernel, new_tab,
reset_namespace, array_inline, array_table, clear_line]
# --- To communicate with the kernel
def silent_execute(self, code):
"""Execute code in the kernel without increasing the prompt"""
try:
if self.is_debugging():
self.pdb_execute(code, hidden=True)
else:
self.kernel_client.execute(str(code), silent=True)
except AttributeError:
pass
def set_backend_for_mayavi(self, command):
"""
Mayavi plots require the Qt backend, so we try to detect if one is
generated to change backends
"""
calling_mayavi = False
lines = command.splitlines()
for line in lines:
if not line.startswith('#'):